Can I get best performance making static variables?

前端 未结 5 477
爱一瞬间的悲伤
爱一瞬间的悲伤 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).

提交回复
热议问题