Can I get best performance making static variables?

前端 未结 5 388
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 07:16

Why some people do:

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

instead of:

char baa(int x) {
          


        
相关标签:
5条回答
  • 2021-02-01 07:56

    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).
    0 讨论(0)
  • 2021-02-01 07:57

    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.

    0 讨论(0)
  • 2021-02-01 08:00

    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.

    0 讨论(0)
  • 2021-02-01 08:14

    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.

    0 讨论(0)
  • 2021-02-01 08:16

    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.

    0 讨论(0)
提交回复
热议问题