I'm a const fiend, and I strive to make everything as const as possible.
I've tried looking at various dissassembly outputs from const and non const versions of functions, and I've yet to see a marked improvement however. I'm assuming compilers nowadays are able to do smart things with non const functions that could technically be const.
Are there still cases where const is useful at the machine level? Any examples?
The const keyword allows a programmer to tell the compiler that a particular variable should not be modified after the initial assignment in its declaration.
The big advantage of const over #define is type checking. #defines can't be type checked, so this can cause problems when trying to determine the data type. If the variable is, instead, a constant then we can grab the type of the data that is stored in that constant variable.
The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).
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.
The primary use of const
isn't to generate better code, but to protect you from yourself, ensuring that you don't accidentally change something you didn't mean to.
It's pretty rare for const to actually help the compiler optimize. You have to keep in mind that the const_cast
can be used anywhere to remove constness from an object (although actually modifying the resulting object isn't always well-defined, it is in some cases, and so the compiler has to be careful about assuming that just because a const object is passed to a function, it won't be modified)
Likewise, the mutable
keyword messes things up. You might pass a const object to a function, but what if that object contains a mutable
field?
The compiler has to do a lot of work to verify that it's safe to assume that an object is really constant -- and by the time it's done all this verification, the const
keyword doesn't really matter, because it could have done all the same analysis on a regular non-const object as well to determine that it isn't being modified and can be treated as constant.
I won't say there aren't a few border cases where the const keyword can enable new optimizations, but in general, const
isn't a performance consideration, but a correctness one. Use it to catch more bugs at compile-time, not to speed up your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With