I understand the behavior of const
-qualified data types. I am curious, though, if there is any performance gain or loss from over- or under-zealousness of quali
const
is mainly a compile-time thing, however, declaring something as const
sometimes allows for certain optimizations. If the code in question isn't a performance bottleneck, I wouldn't worry about it and just use const
as intended: to produce clearer code and prevent yourself from doing stupid things.
While the answer is technically "yes", the practical answer is NO. It's true that the compiler can, under certain circumstances, perform code optimizations by taking into account that a given value cannot change or that a method will not modify the owning object. However, these will be situational cases and so incredibly far down in the weeds of optimization that it would almost certainly be a mistake to take it into account up front.
My understanding is that const can be used by the compiler to potentially optimize performance, but is no guarantee of such; there shouldn't be a performance downside, though. It could potentially affect runtime behavior (ie: the compiler could put const variables on read-only memory pages).
It should not have a significant impact on performance, but I'd error on using it more for ease of code maintenance. Just my opinion, though.
const
is just there to help you catch errors at compile time. However since there's this thing called the const_cast
you can always change the constness of any variable so the compiler really can't get away with optimizing anything away. (You can also have fun with c-style casts to get rid of constness which could make optimizations invalid.)
In my (limited) experience, const CAN hurt the performance by quite a lot (surprise!) Namely, when working with container classes be careful what cont-ness does: for arrays it might simply force the compiler to create a copy of your container (e.g., an array) once a single element is accessed for reading only... This was a huge pain to locate in the code that I am working on.