const正确性能提高性能吗? [英] Can const-correctness improve performance?
问题描述
因此,你有例子,const正确性可以帮助你的编译器提高你的程序的性能?
const
正确性无法提高性能,因为 const_cast
和 mutable
是在语言中,并允许代码一致地违反规则。这在C ++ 11中变得更糟,其中你的 const
是指向 std :: atomic
的指针,意味着编译器必须尊重其他线程所做的更改。
也就是说,编译器查看它生成的代码并确定它是否实际写入给定的变量,并相应地应用优化是微不足道的。
, const
正确性是关于可维护性的好的东西。否则,您的类的客户端可能会破坏该类的内部成员。例如,考虑标准 std :: string :: c_str()
- 如果它不能返回一个const值,你可以拧紧内部缓冲区的字符串!
出于性能原因不要使用 const
。由于可维护性原因,请使用它。
I have read numerous times that enforcing const-correctness in your C or C++ code is not only a good practice with regards to maintainability, but also it may allow your compiler to perform optimizations. However, I have read the complete opposite, too — that it does not affect performance at all.
Therefore, do you have examples where const correctness may aid your compiler with improving your program's performance?
const
correctness can't improve performance because const_cast
and mutable
are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const
data may e.g. be a pointer to a std::atomic
, meaning the compiler has to respect changes made by other threads.
That said, it is trivial for the compiler to look at the code it generates and determine if it actually writes to a given variable, and apply optimizations accordingly.
That all said, const
correctness is a good thing with respect to maintainability. Otherwise, clients of your class could break that class's internal members. For instance, consider the standard std::string::c_str()
-- if it couldn't return a const value, you'd be able to screw around with the internal buffer of the string!
Don't use const
for performance reasons. Use it for maintainability reasons.
这篇关于const正确性能提高性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!