Do temp variables slow down my program?
A modern optimizing compiler should optimize those variables away, for example if we use the following example in godbolt with gcc
using the -std=c99 -O3
flags (see it live):
#include <stdio.h>
void func()
{
int i = 5;
int j = 10;
int result = i + j;
printf( "%d\n", result ) ;
}
it will result in the following assembly:
movl $15, %esi
for the calculation of i + j
, this is form of constant propagation.
Note, I added the printf
so that we have a side effect, otherwise func
would have been optimized away to:
func:
rep ret
These optimizations are allowed under the as-if rule, which only requires the compiler to emulate the observable behavior of a program. This is covered in the draft C99 standard section 5.1.2.3
Program execution which says:
In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).
Also see: Optimizing C++ Code : Constant-Folding
This is an easy task to optimize for an optimizing compiler. It will delete all variables and replace result
with 15
.
Constant folding in SSA form is pretty much the most basic optimization there is.
The example you gave is easy for a compiler to optimize. Using local variables to cache values pulled out of global structures and arrays can actually speed up execution of your code. If for instance you are fetching something from a complex structure inside a for loop where the compiler can't optimize and you know the value isn't changing, the local variables can save quite a bit of time.
You can use GCC (other compilers too) to generate the intermediate assembly code and see what the compiler is actually doing.
There is discussion of how to turn on the assembly listings here:Using GCC to produce readable assembly?
It can be instructive to examine the generated code and see what a compiler is actually doing.