Suppose I have a function in a single threaded program that looks like this
void f(some arguments){
char buffer[32];
some operations on buffer;
}
and f appears inside some loop that gets called often, so I'd like to make it as fast as possible. It looks to me like the buffer needs to get allocated every time f is called, but if I declare it to be static, this wouldn't happen. Is that correct reasoning? Is that a free speed up? And just because of that fact (that it's an easy speed up), does an optimizing compiler already do something like this for me?
Out of five memory areas that JVM uses, the static fields are allocated memory in Class Area(part of PremGen) when the class is loaded by the Application class loader during prepare and loading phase.
Static variables saves memory over local variables of a function due to recursive calls it makes, which allocates a new set of variables each time. All the static variables are allocated and initialized only once at the start of the program.
Static variables may actually slow you down as its some aggresive optimisations are not possible on static variables. Also as locals are in a contiguous area of the stack they are easier to cache efficiently.
No, local variables do not normally stay in memory (they get freed) but if a closure is formed then it MUST stay in memory because it is still in use.
No, it's not a free speedup.
First, the allocation is almost free to begin with (since it consists merely of adding 32 to the stack pointer), and secondly, there are at least two reasons why a static variable might be slower
So it's not a free speedup. But it is possible that it is faster in your case (although I doubt it). So try it out, benchmark it, and see what works best in your particular scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With