views:

172

answers:

4

Just wondering is this kind of code recommended to increase performance?

void functionCalledLotsofTimes() {
   static int *localarray = NULL;

   //size is a large constant > 10 000
   if (localarray == NULL) localarray = new int[size];  

   //Algorithm goes here
}

I'm also curious how static variables are implemented by modern c++ compilers like g++. Are they handled like global variables?

+12  A: 

It is not recommended because you are introducing global state to a function. When you have global state in a function you have side effects. Side effects cause problems especially in multi threaded programs.

See Referential Transparency for more information. With the same input you always want to have the same output, no matter how many threads you use.

If you want to enable more efficiency, allow the user to specify the buffer themselves as one of the parameters.

See the difference between global and static variables here.

Brian R. Bondy
A: 
lsalamon
A: 

If I'm not mistaken, the test to see if the static variable has already been initialized is done by "the system" anyway. No need to do it yourself. Just write

static int *localarray = new int[size];

Only the first time the function is called, the array will be created.

FredOverflow
A: 

Usually that kind of code is hidden behind a custom allocator class that has a large pre-allocated buffer, so that "dynamic allocations" actually aren't.

Many implementations of std::vector have a more basic form of implementation of this: by default it allocates "blocks" of memory in powers of two, so that no real new allocations need to be done until after the vector has grown to twice the size.

MadKeithV