A friend told me that it's more efficient to do
int addNumbers(const int number1, const int number2);
than
int addNumbers(int number1, int number2);
assuming of course that number1
and number2
won't be assigned new values. Does this result in a significant performance boost? Are there any other side effects I should know about?
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.
For a function parameter passed by value, const has no effect on the caller, thus is not recommended in function declarations.
Declaring function parameters const indicates that the function promises not to change these values. In C, function arguments are passed by value rather than by reference. Although a function may change the values passed in, these changed values are discarded once the function returns.
No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.
const correctness
is more of letting compiler help you guard against making honest mistakes. Declaring the const-ness of a parameter is just another form of type safety rather than a boost for performance.
Most of the modern compiler will be able to detect if a variable is really constant or not, and apply correct optimizations. So do not use const-correctness for performance reasons. rather use it for maintainability reasons & preventing yourself from doing stupid mistakes.
I hope you are aware that in terms of function declarations these two are identical, that is they declare the same function!!!
Now, as far as the definitions go, I can't say if there's any boost at all, but I can promise you there is no significant boost. I don't believe modern compilers are stupid. Most of them are smarter than you and I. ))
There's another side. Some programmers will prefer to add const wherever it's applicable, to be genuinely const-correct. This is a valid point of view and practice. But again, I wouldn't do it just for performance issues.
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