Case Study in Optimization: Faster SPI on AVRs

The Arduino Library provides functions like shiftOut() and digitalWrite().  These functions are simple and effective, but they are slow. Of course, they’re doing a lot more than just toggling bits. Faster isn’t always necessary and can sometimes lead to more difficult debugging.  And as Donald Knuth said,

…premature optimization is the root of all evil.

So what happens, when you do need to optimize? For example, if shiftOut() is too slow for your project, what do you do?  In Ralph’s post, Fastest AVR software SPI in the West, he breaks down different SPI code implementations into their assembly code.

To make the best optimization, you need to change compiler flags. So this is, in my opinion, an interesting case study in what kind of performance benefit you can get when you do some serious optimization.

Of course, you really shouldn’t, unless you need it…

Check out his post: Fastest AVR software SPI in the West

Knuth quote from his paper “StructuredProgrammingWithGoToStatements.”

Fan of making things beep, blink and fly. Created AddOhms. Writer for News. Freelance electronics content creator for hire! KN6FGY and, of course, bald.


  1. I’ll see your Knuth quote, and raise you with an Einstein quote: “Unthinking respect for authority is the greatest enemy of truth.”
    The big caveat in Knuth’s quote is how you define “premature”. I focus on making lean/efficient code, and try to avoid optimizations that increase code size and complexity. Less code is easier to maintain and understand.

  2. Changing the compiler flags may help in this case. But you can simply inline this assembler thing and make a nice template out of it. Then you can use this with any Arduino pin, very simple, from the ide, without any modification.

Write A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.