Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variables in functions

Tags:

c

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)

like image 537
Ulterior Avatar asked Dec 09 '22 07:12

Ulterior


2 Answers

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.

like image 132
roni bar yanai Avatar answered Dec 27 '22 10:12

roni bar yanai


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.

like image 33
Jerry Coffin Avatar answered Dec 27 '22 11:12

Jerry Coffin