Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Memory in C++

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?

like image 534
aramadia Avatar asked Dec 18 '22 02:12

aramadia


1 Answers

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.

like image 113
Brian R. Bondy Avatar answered Jan 03 '23 14:01

Brian R. Bondy