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?
constcorrectness can’t improve performance becauseconst_castandmutableare in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where yourconstdata may e.g. be a pointer to astd::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,
constcorrectness is a good thing with respect to maintainability. Otherwise, clients of your class could break that class’s internal members. For instance, consider the standardstd::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
constfor performance reasons. Use it for maintainability reasons.