---
title: "Case Study in Optimization: Faster SPI on AVRs"
description: "The Arduino Library provides functions like (http://arduino.cc/en/Reference/shiftOut \"Arduino reference for shiftOut()\") and (http://arduino.cc/en/Reference/digitalWrite…"
canonical: "https://www.baldengineer.com/case-study-in-optimization-faster-spi-on-avrs.html"
author: "James Lewis"
date: "2015-03-30T13:03:48Z"
lastmod: "2017-05-08T13:35:02Z"
categories: ["arduino","around-the-web","programming"]
tags: []
---

# Case Study in Optimization: Faster SPI on AVRs


The Arduino Library provides functions like [shiftOut()](http://arduino.cc/en/Reference/shiftOut "Arduino reference for shiftOut()") and [digitalWrite()](http://arduino.cc/en/Reference/digitalWrite "Arduino Reference for 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](http://c2.com/cgi/wiki?DonKnuth "Background on author 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](http://nerdralph.blogspot.com/2015/03/fastest-avr-software-spi-in-west.html "Optimized SPI Code for AVRs"), 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](http://nerdralph.blogspot.com/2015/03/fastest-avr-software-spi-in-west.html "Optimized SPI Code for AVRs")

Knuth quote from his paper "[StructuredProgrammingWithGoToStatements](http://wiki.c2.com/?PrematureOptimization "Donald Knuth's Famous \"GoTos aren't bad\" paper")."

