In embedded systems (I'm using C++ and Arduino) within a continuously repeating main loop(), is it more efficient to define a temporary variable each time or to define a global variable once and update it in each iteration?
Solution 1
int temporary_variable_global = 0;
void loop() {
//... Imagine having the codes above ...
temporary_variable_global = x + 3;
//... Imagine having the codes below ...
}
Solution 2
void loop() {
//... Imagine having the codes above ...
int temporary_variable_local = x + 3;
//... Imagine having the codes below ...
}
Which solution is better for performance and execution time? I googled this question but couldn't find a clear answer.
Note: I'm not looking for an answer to this question for desktop programs or the web. For embedded systems only.
Preface
The ultimate way to decide such question is to look into the generated machine code. I leave this as an exercise for you. Your finding holds true only for the specific program compiled with the specific compiler with the specific flags. You may not generalize it, so it is clear that you cannot find a "clear answer."
However, the following is an abstract view based on personal experience with GCC for AVR, in times on Arduino, but also on "pure metal." It is short of academic considerations, take it with a grain of caution.
The Relevant Stuff
A global variable is commonly allocated in memory. With the modifier
staticto limit the scope to the translation unit, some smart compiler might decide to place it in a register, however.A local variable has a high probability of being held in a register. This depends heavily on the number of other variables, potentially inlined functions, and calculations done, at least. It might be allocated on the stack, which is memory.
Accesses of registers are faster than accesses of memory cells.
Therefore, I'd say a local variable will not be slower, but is often faster.
Note
Before diving into the "machine room" think about the necessity to optimize in such a way. Beginners often optimize prematurely and without being urged, and it makes their code worse.
Please write your source in the best way you can. Yes, you want the compiler to produce something that realizes your intent, and so you need be clear for it. But the main readers are all future developers including yourself. Make yourself as clear as possible. Narrow the scope of each object as much as possible.
Optimize only, if the program executes outside the requirements, for example on memory size or execution speed. You have factual requirements, don't you?