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?
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.
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