静态变量会阻碍数据缓存吗? [英] Do Static Variables Impede Data Caching?

查看:97
本文介绍了静态变量会阻碍数据缓存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自使用C ++优化软件(第7.1节)


静态数据的优点是可以在程序启动前将其初始化为所需的
值。缺点是,即使
变量仅在程序的一小部分中使用,在整个程序执行过程中也会占用内存
空间。 这使数据
的缓存效率降低。

的用法static ,除了它在静态存储持续时间的确切情况下适用于C和C ++。

The usage of static in this except is as it applies to both C and C++ in the exact case of static storage duration.

任何人都可以阐明一下为什么(或是否)静态持续时间变量的数据缓存效率较低?这是一个具体的比较:

Can anyone shed some light on why (or whether) data caching is less efficient for static duration variables? Here is a specific comparison:

void foo() {
  static int static_arr[] = {/**/};
}
void bar() {
  int local_arr[] = {/**/};
}

我看不出任何原因会导致静态数据与其他任何数据的缓存方式不同一种数据。在给定的示例中,我认为 foo 会更快,因为执行堆栈不必加载 static_arr ,而在 bar 中,执行堆栈必须加载 local_arr 。在这两种情况下,如果重复调用这些函数,则将同时缓存 static_arr local_arr 。我错了吗?

I don't see any reason why static data would cache differently than any other kind of data. In the given example, I would think that foo will be faster because the execution stack doesn't have to load static_arr, whereas in bar, the execution stack has to load local_arr. In either case, if these functions were called repeatedly, both static_arr and local_arr will be cached. Am I wrong?

推荐答案

rustyx的回答解释了这一点。局部变量存储在堆栈中。当函数返回时释放堆栈空间,并在调用下一个函数时重新使用堆栈空间。局部变量的缓存效率更高,因为相同的存储空间可以一次又一次地被重用,而静态变量则分散在不同的存储器地址中,而这些地址永远都不能再用于其他目的。静态数据是存储在DATA节中(初始化)还是BSS节(未初始化)在这方面没有区别。栈顶空间很可能会在程序执行期间一直保持缓存状态,并且可以重复使用多次。

The answer from rustyx explains it. Local variables are stored on the stack. The stack space is released when a function returns and reused when the next function is called. Caching is more efficent for local variables because the same memory space is reused again and again, while static variables are scattered around at different memory addresses that can never be reused for another purpose. Whether static data are stored in the DATA section (initialized) or the BSS section (uninitalized) makes no difference in this respect. The top-of-stack space is likely to stay cached throughout program execution and be reused many times.

另一个优点是,可以使用以下方式访问数量有限的局部变量:相对于堆栈指针的8位偏移量,而静态变量则需要32位的绝对地址(在32位x86中)或32位的相对地址(在x86-64中)。换句话说,局部变量可以使代码更紧凑,并提高代码缓存和数据缓存的利用率。

Another advantage is that a limited number of local variables can be accessed with an 8-bit offset relative to the stack pointer, while static variables need a 32-bit absolute address (in 32-bit x86) or a 32-bit relative address (in x86-64). In other words, local variables may make the code more compact and improve utilization of the code cache as well as the data cache.

// Example
int main () {
  f();
  g();
  return 0;
}

void f() {
   int x; 
   ...
}

void g() {
   int y;  // y may occupy the same memory address as x
   ...
}

这篇关于静态变量会阻碍数据缓存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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