Is there a performance issue using static variables in function calculations, does it affect speed of function execution, as static variables are initialized only once?
Question is for a highly repetetive calling optimizations.
Consider this example
int calcme(int a, int b)
{
static int iamstatic = 20;
return a*iamstatic + b;
}
The reason to use static is to hope, that iamstatic will not be put on stack every time a function is called and it is designed to change if needed. (Static variable change code is ommited)
To my opinion you might reduce performance. When you use static, the memory is located at the bss part for the program. When the function is called it a access two different locations, the function memory and the parameter memory. If it is local then you may gain performance due to localization, when all parameters are at the same cache line, that is when the cpu read memory it reads a full cache line (16 bytes is a common size of line), you read all the data in one memory access into the cache.
Yes. In your example, it probably won't help (at least enough to care about). In fact, it might even hurt a bit, because it's likely to involve loading the data from memory where a local might just involve loading a value into a register. If the initialization is slow enough for the performance to matter, making the variable static
can improve performance as long as only being initialized once is acceptable.
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