Can I get best performance making static variables

2019-03-15 09:09发布

Why some people do:

char baa(int x) {
    static char foo[] = " .. ";
    return foo[x ..];
}

instead of:

char baa(int x) {
    char foo[] = " .. ";
    return foo[x ..];
}

looks like very common on linux source codes applications. There performance difference? if yes, can someone explain why? Thanks in advance.

5条回答
Root(大扎)
2楼-- · 2019-03-15 09:41

Yes it makes difference , if u have declared a variable as static :

  1. Firstly, the memory will be allocated in either bss or data segment instead of stack.

  2. Secondly, it will be initialized for once only , not every time unlike other variables of function, which will surely create difference.

  3. Thirdly, it retains it's value b/w function calls.So depending on the situations you should use it.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-15 09:42

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-03-15 09:46

Defining a variable static in a method only means that the variable is not "released", i.e. it will keep its value on subsequent calls. It could lead to performance improvement depending on the algorithm, but is certainly not not a performance improvement by itself.

查看更多
我命由我不由天
5楼-- · 2019-03-15 09:48

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,

  • is likely to be quicker
  • may use less memory
  • will use less stack space (which on some systems is a scarce resource)
  • will play nicer with the cache (which isn't likely to be a big deal for a small string, but might be if foo is something bigger).
查看更多
我想做一个坏孩纸
6楼-- · 2019-03-15 09:51

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.

查看更多
登录 后发表回答