局部数组和静态const局部数组之间的性能和内存差异是什么?

huangapple go评论66阅读模式
英文:

What are the performance and memory differences between a local array and a static const local array?

问题

我正在尝试决定是否使用

int x[] = {/一些数字/};

还是

static const int x[] = {/一些数字/};

我理解第一个版本会在每次函数调用时重新创建数组,这似乎是浪费的,而第二个版本将创建一个仅由函数访问的全局变量,内存距离可能不太高效。(const 只是 C 语言中的修饰符,用来表示这些数字不会改变)。

我最初将数组放在全局范围内,但后来我认为将作用范围限制在函数内可能更好。当然,也许最好的方法是正常做,每次都重新创建数组。我不知道。

英文:

I am trying to decide whether to use

int x[] = {/*some numbers*/};

or

static const int x[] = {/*some numbers*/};

My understanding is that the first version will remake the array every function call, which seems wasteful, while the second will make a global variable accessible only by the function, and the memory distance might be less performant. (const is just there for decoration in C, and to show you that the numbers won't change).

I first made the array in global scope, but then I thought it might be better to limit the scope. Ofcourse, maybe the best thing to do would be to just do it normal and have the array remade every time. I don't know.

答案1

得分: 3

是的,static const 很可能表现得更好,而且永远不会比没有修饰符的情况差。没有修饰符的情况下,数据有可能在每次函数调用时加载到堆栈上。

尽量减小作用域是一个良好的实践。

> 在C中,const 只是用来装饰的,用来告诉你数字不会改变

这并不是真的,尤其是在像微控制器这样的ROM-based系统上,const 经常决定了内存分配和闪存分配之间的区别。

此外,const 还涉及一些与指针别名决策相关的更微妙的事情,这意味着在某些情况下它可以提高性能。查看我的最近回答 https://stackoverflow.com/a/75854539/584518。在这些示例中,有几种情况下,static 和/或 const 可以提高性能。

英文:

Yes static const will likely perform better and never worse than the alternative without qualifiers. Without them there's a chance that the data will get loaded onto the stack at each function call.

Reducing the scope as much as possible is good practice.

> const is just there for decoration in C, and to show you that the numbers won't change

This isn't true, especially not on ROM-based systems like microcontrollers. On those systems, const often makes the difference between RAM allocation and flash allocation.

Furthermore, there's a bunch of more subtle things related to const such as pointer aliasing decisions made by the compiler, meaning it can improve performance in some situations. Check out my recent answer at https://stackoverflow.com/a/75854539/584518. There are several situations in those examples where static and/or const improves performance.

huangapple
  • 本文由 发表于 2023年4月4日 14:09:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定