Can function calls be speeded up by declaring local variables as static? It seems logical because a few stack allocations can be avoided for each call. If it is indeed the case, why isn't this used very often?
c function call performance
Collapse
X
-
A local static variable is a form of global variable. It is available to every function call. That means if the function is called simulatanouesly from two threads, each call will use the same variable. This sets up a thing called a race condition and that can cause your program to spin out of control.
I could go on but there is an article in the C/C++ HowTos titled: The Case Against Global Variables. I suggest you take a look. -
You're right that declaring locals as static would result in fewer stack allocations. There are a couple of reasons why you might want to avoid doing this, though:Originally posted by manu1001Can function calls be speeded up by declaring local variables as static? It seems logical because a few stack allocations can be avoided for each call. If it is indeed the case, why isn't this used very often?
1) Your code will be slightly uglier, as you'll still have to initialise the variable as well as declare it:
[code=c]
void func()
{
static int var = 0;
var = 0; // initialise it for subsequent calls
...
}
[/code]
2) Your function becomes non-reentrant.
In addition, you probably still want to use locals for integer-sized (ints, pointers etc.) variables in order to allow the compiler to store them in registers rather than on the stack.
In summary, trust your compiler to do the right thing, and leave this kind of optimisation until the stage where you've nailed all the other inefficient bits and are ready to starting in-lining assembler in your C code.Comment
-
Your assumption that each extra local variable would have to be separately allocated from the stack is at fault on many systems.Originally posted by manu1001Can function calls be speeded up by declaring local variables as static? It seems logical because a few stack allocations can be avoided for each call. If it is indeed the case, why isn't this used very often?
Often what happens is that the stack pointer is moved during a function call to allow room on the stack for all the local variables. This is a single write, usually to a processor register weather you have 0, 1, 12 or however many local variables.
This is of course very generalised and in practice it is completely down to the actual platform you are using (and the language to some extent I believe C and C++ handle the stack differently particularly the epilogue at the end of a function call).
However normally having more local variables does not make any(much) difference to function call efficiency. So you argument for using static variables is flawed and as weaknessforcats has pointed out using static variables has its own set of problems.Comment
Comment