17

为什么有些人声明将他们的变量设为静态,如下所示:

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

代替:

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

它似乎在 Linux 源代码应用程序中很常见。有性能差异吗?如果是,有人可以解释为什么吗?提前致谢。

4

5 回答 5

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.

于 2012-05-09T23:52:32.480 回答
9

在典型的实现中,带有的版本static只会在编译时将字符串放在内存中的某个位置,而没有的版本static将使函数(每次调用它)在堆栈上分配一些空间并将字符串写入该空间。

static因此,带有 的版本

  • 可能会更快
  • 可能会使用更少的内存
  • 将使用更少的堆栈空间(在某些系统上是稀缺资源)
  • 会更好地使用缓存(对于一个小字符串来说这可能不是什么大问题,但可能foo是更大的东西)。
于 2012-05-09T23:55:24.087 回答
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.

于 2012-05-09T23:52:04.617 回答
2

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.

于 2012-05-09T23:52:33.517 回答
2

是的,如果您已将变量声明为静态变量,则会有所不同:

  1. 首先,内存将分配在 bss 或数据段而不是堆栈中。

  2. 其次,它只会初始化一次,不像函数的其他变量那样每次都会初始化,这肯定会产生差异。

  3. 第三,它保留了它的价值 b/w 函数调用。所以根据你应该使用它的情况。

于 2012-05-10T08:53:14.540 回答