No, const
does not help the compiler make faster code. Const
is for const-correctness, not optimizations.
The C++ standard says that const
items can't be modified, but also says that const_cast
should remove the const
modifier from an object and make it writable (unless it's located in actually read-only memory, in which case the behavior is undefined); as such const
cannot mean, in general, that the target variable will not change.
I can only think of these two very narrow scenarios where having const
produces faster code than not having it:
- the variable is global with internal linkage (
static
) and is passed by reference or pointer to a function defined in a different translation unit (different file). In this case, the compiler cannot elide reads to it if it is not marked const
;
- the variable is global with external linkage (
extern
). Reads to a const extern
can be elided inside the file that defines it (but nowhere else).
When const
is applied to a global variable, the compiler is allowed to assume that the value will never change because it will place it in read-only memory, and this means undefined behavior if the program attempts to modify it, and compiler authors love to rely on the threat of undefined behavior to make code faster.
Note that both scenarios apply only to global variables, which probably make for a very minor portion of the variables in your program. To its merit, however, const
implies static
at the global level in C++ (this is not the case in C).
Someone above said that using const
can make code faster because it's possible to use const
references. I would argue here that what make the code faster is the use of a reference, not the use of const
.
That said, I still believe const
is a very sharp knife with which you can't cut yourself and I would advise that you use it whenever it's appropriate, but don't do it for performance reasons.