Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can static local variables cut down on memory allocation time?

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?

like image 867
pythonic metaphor Avatar asked Sep 16 '10 19:09

pythonic metaphor


People also ask

How many times memory was allocated for static variable?

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.

Do static variables take up memory?

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.

Are static variables slow?

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.

Do local variables take up memory?

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.


1 Answers

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

  • you lose cache locality. Data allocated on the stack are going to be in the CPU cache already, so accessing it is extremely cheap. Static data is allocated in a different area of memory, and so it may not be cached, and so it will cause a cache miss, and you'll have to wait hundreds of clock cycles for the data to be fetched from main memory.
  • you lose thread safety. If two threads execute the function simultaneously, it'll crash and burn, unless a lock is placed so only one thread at a time is allowed to execute that section of the code. And that would mean you'd lose the benefit of having multiple CPU cores.

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.

like image 160
jalf Avatar answered Nov 11 '22 12:11

jalf