Can I get best performance making static variables?

前端 未结 5 424
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题