Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does const'ing primitive types in function parameters result in a significant performance boost?

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?

like image 976
Pieter Avatar asked Jun 18 '11 14:06

Pieter


People also ask

Does using const improve performance?

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.

What effect does the const keyword have on a function parameter?

For a function parameter passed by value, const has no effect on the caller, thus is not recommended in function declarations.

Why might it be good for a function parameter to be const?

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.

Does const make code faster?

No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.


2 Answers

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.

like image 186
Alok Save Avatar answered Sep 21 '22 21:09

Alok Save


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.

like image 34
Armen Tsirunyan Avatar answered Sep 22 '22 21:09

Armen Tsirunyan