c++optimizationcompiler-constructioncompiler-optimizationconst-correctness

Constants and compiler optimization in C++


I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtains.

For example, how does the compiler optimize a method that is declared const vs one that isn't but should be. What happens when you introduce mutable variables? Do they affect these optimizations of const methods?


Solution

  • Let’s disregard methods and look only at const objects; the compiler has much more opportunity for optimization here. If an object is declared const, then (ISO/IEC 14882:2003 7.1.5.1(4)):

    Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

    Let’s disregard objects that may have mutable members. The compiler is free to assume that the object will not be and modified, therefore it can produce significant optimizations. These optimizations can include things like:

    Note that this stuff applies only if the actual object is const. It does not apply to objects that are accessed through const pointers or references because those access paths can lead to objects that are not const (it's even well-defined to change objects though const pointers/references as long as the actual object is non-const, and you cast away the constness of the access path to the object).

    In practice, I don't think there are compilers out there that perform any significant optimizations for all kinds of const objects. But for objects that are primitive types (ints, chars, etc.), I think that compilers can be quite aggressive in optimizing the use of those items.