我是否通过使变量静态来提高性能? [英] Do I get improved performance by making variables static?

查看:26
本文介绍了我是否通过使变量静态来提高性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有些人声明让他们的变量是静态的,就像这样:

Why do some people declare make their variables static, like so:

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

代替:

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

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

It seems to be very common on Linux source codes applications. Is there any performance difference? If yes, might someone explain why? Thanks in advance.

推荐答案

它不是为了性能本身,而是为了减少内存使用.有性能提升,但这不是(通常)您看到类似代码的主要原因.

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.

然而,静态变量存储在 .BSS.DATA 段中(非显式初始化的静态变量将转到 .BSScode>,静态初始化的静态变量将进入 .DATA),离开堆栈.编译器还可以利用这一点来执行某些优化.

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.

这篇关于我是否通过使变量静态来提高性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆