gpt4 book ai didi

c++ - 静态变量会阻碍数据缓存吗?

转载 作者:太空狗 更新时间:2023-10-29 19:42:59 28 4
gpt4 key购买 nike

来自 Optimizing Software in C++ (Section 7.1) ,

The advantage of static data is that it can be initialized to desired values before the program starts. The disadvantage is that the memory space is occupied throughout the whole program execution, even if the variable is only used in a small part of the program. This makes data caching less efficient.

except 中 static 的用法是因为它在静态存储持续时间的确切情况下适用于 C 和 C++。

谁能阐明为什么(或是否)数据缓存对于静态持续时间变量的效率较低?下面是具体对比:

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

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

最佳答案

一般来说,Agner Fog 通常知道他在说什么。

如果我们阅读 7.1 不同类型的变量存储 部分的上下文中的引述,我们就会明白他在文章开头所说的“效率较低的缓存”是什么意思部分:

Data caching is poor if data are scattered randomly around in the memory. It is therefore important to understand how variables are stored. The storage principles are the same for simple variables, arrays and objects.

所以说 static 变量的缓存效率较低背后的想法是,存储它们的内存位置“冷”(不再在缓存中)的可能性大于堆栈内存,这是存储自动存储持续时间的变量的地方。

考虑到缓存和分页,影响性能的是数据存储的物理和时间局部性的组合。

关于c++ - 静态变量会阻碍数据缓存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743186/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com