Why do some people declare make their variables static, like so:
char baa(int x) {
static char foo[] = " .. ";
return foo[x ..];
}
instead of:
char baa(int x) {
char foo[] = " .. ";
return foo[x ..];
}
It seems to be very common on Linux source codes applications. Is there any performance difference? If yes, might someone explain why? Thanks in advance.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Using static variables may make a function a tiny bit faster. However, this will cause problems if you ever want to make your program multi-threaded. Since static variables are shared between function invocations, invoking the function simultaneously in different threads will result in undefined behaviour.
Benefits of static variables: constants can be defined without taking additional memory (one for each class) constants can be accessed without an instantiation of the class.
Static variables When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
It's not for performance per se, but rather to decrease memory usage. There is a performance boost, but it's not (usually) the primary reason you'd see code like that.
Variables in a function are allocated on the stack, they'll be reserved and removed each time the function is called, and importantly, they will count towards the stack size limit which is a serious constraint on many embedded and resource-constrained platforms.
However, static variables are stored in either the .BSS
or .DATA
segment (non-explicitly-initialized static variables will go to .BSS
, statically-initialized static variables will go to .DATA
), off the stack. The compiler can also take advantage of this to perform certain optimizations.
In typical implementations, the version with static
will just put the string somewhere in memory at compile time, whereas the version without static
will make the function (each time it's called) allocate some space on the stack and write the string into that space.
The version with static
, therefore,
foo
is something bigger).Yes, the performance is different: unlike variables in the automatic storage that are initialized every time, static variables are initialized only once, the first time you go through the function. If foo
is not written to, there is no other differences. If it is written to, the changes to static variables survive between calls, while changes to automatic variables get lost the next time through the function.
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