Menu

Should I use global or local variables?

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 it's up the reader to assess to what extent.

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 (Arduino's) is a costly operation: it takes at least 3 instructions to update a variable (load from RAM, change register, store back to RAM) instead of just one 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.

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.

  • Use local variables (you know that by now).
  • Make the scope of your local variables as small as possible.
  • Make your variable const if they don't change in their scope (the above makes it easier).
  • Don't use a local variable if it's only used by the next instruction and never afterwards.
  • Split functional blocks into functions.
  • Make your functions as small as possible.
  • Use global variables only if inevitable.
Posted by Vince C. 2021-08-21 | Draft

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.