Let's first set the context: since Harduino is a project mostly related to the 8-bit AVR architecture, this article focuses on the latter, mostly. However the generalizations do apply to any other — and not limited to 8-bit — architecture although the reader should be wise enough to assess to what extent. The wary of us will also argue this is also mitigated by compiler optimizations, which could, in some circumstances, make the use of global variables completely irrelevant. However
AVR microcontrollers have 32 registers. That in and on itself greatly helps reduce RAM usage by using registers instead of the stack for local variables.
So comes the question: why is it that important to use local variables instead of global and why should I care?
The answer is simple: using RAM (mind stack is RAM) on AVR microcontrollers generally is a costly operation as it takes at least 3 instructions to update a variable, i.e.
Instead, only one is required when only registers are involved. Here's for instance how an instruction such as a1++
could look like — let's say a1 is a 16-bit integer:
80 91 02 01 lds r24, 0x0102 ; 0x<a1>
90 91 03 01 lds r25, 0x0103 ; 0x<a1+0x1>
01 96 adiw r24, 0x01 ; 1
90 93 03 01 sts 0x0103, r25 ; 0x<a1+0x1>
80 93 02 01 sts 0x0102, r24 ; 0x<a1>
First the variable is loaded in a register pair, r24
and r25
, then incremented and stored back into RAM. Note that it takes only one instruction to increment the register pair. Also note that it takes as many assembly instructions to load/store a variable as the variable size in bytes on an 8-bit architecture such as found on an Arduino Uno/Nano (ATmega328) Micro (ATmega32U4) and many others.
If you have only global variables, your program is at least 3 times slower to access those variables. And if you have too many local variables, the compiler will be forced to use the stack instead of registers.
So what?
The obvious benefit of local variables is you're telling the compiler that those storage spaces are disposable and it's not required to dedicate registers to those storage areas! And since AVR has a lot of registers, that makes a lot of opportunities to use them instead of the stack. As a consequence, your program runs faster and is less resource hungry, which is critical on a microcontroller that only has two thousand bytes of RAM for you to play with.
Here's a couple of hints.