Does const'ing primitive types in function parameters result in a significant performance boost?
A friend told me that it's more e开发者_开发百科fficient 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
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.
This would be micro-optimisation at best; wrong at worst.
Don't bother with ideas like this.
If you are not going to change the value, use const
. And move on.
You may be thinking of something like this:
void foo(vector<int> large_object)
vs.
void foo(const vector<int>& large_object)
The second case may be faster because the compiler will only push a reference on the stack. In the first case the entire vector will be pushed.
This probably depends on the compiler and the nature of the function, the there isn't really any room for optimization. If you think about the compiler's job of choosing when to use CPU registers and which load instruction to use, I can not find any use cases where knowing that a parameter is const will allow the compiler to optimize code.
However, you should still use const in your function declarations. It is self documenting and lets others know the nature of the parameters. Also, it might prevent you from doing something unintentionally with a variable:
void addNumbers(const int num1, const int num2)
{
...
num1++; // you really didn't mean to do this!
}
精彩评论