Alex Rivera | Logout

Do I get improved performance by making variables static?

Asked 2012-05-09T23:47:29.263
17

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.

Edit
Report

2 Answers

20

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.

answered 2012-05-09T23:52:32.480
3

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.

answered 2012-05-09T23:52:04.617

Your Answer