gpt4 book ai didi

c++ - 我应该将 const 用于局部变量以进行更好的代码优化吗?

转载 作者:IT老高 更新时间:2023-10-28 12:37:13 28 4
gpt4 key购买 nike

对于没有被修改的局部变量,我经常使用const,像这样:

const float height = person.getHeight();

我认为它可以使编译后的代码可能更快,允许编译器进行更多优化。还是我错了,编译器可以自己弄清楚局部变量永远不会被修改?

最佳答案

Or am I wrong, and compilers can figure out by themselves that the local variable is never modified?

大多数编译器都很聪明,可以自己解决这个问题。
您应该使用 const 来确保 const-correctness 而不是微优化。
const 正确性 让编译器帮助您防止犯诚实的错误,因此您应该尽可能使用 const,但出于可维护性的原因 & 防止自己犯愚蠢的错误

了解我们编写的代码对性能的影响是件好事,但应避免过度的微优化。关于性能,一个应该遵循的,

80-20 规则:

Identify the 20% of your code which uses 80% of your resources, through profiling on representative data sets and only then attempt to optimize those bottlenecks.

关于c++ - 我应该将 const 用于局部变量以进行更好的代码优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10747927/

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