Do primitive types in functional parameters compare a significant increase in performance?

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 will not be assigned new values. Does this lead to a significant increase in productivity? Are there any other side effects I should be aware of?

+7
source share
5 answers

const correctness is more than that that allows the compiler to help you guard against honest errors. Declaring a parameter constant is another form of type safety, not a performance improvement.

Most modern compilers will be able to determine whether a variable is really constant or not, and apply the correct optimization. Therefore, do not use const-correctness for performance reasons . rather, use it for maintainability reasons and to prevent stupid mistakes .

+11
source

I hope you know that from the point of view of function declarations, these two are identical , that is, they declare the same function !!!

Now, with regard to definitions, I canโ€™t say if there are any enhancements, but I can promise you that there is no significant increase. I don't think modern compilers are stupid. Most of them are smarter than you and me.))

There is another side. Some programmers will prefer to add const wherever applicable to be truly const-correct . This is a valid point of view and practice. But then again, I would not do this just for performance issues.

+8
source

At best, it will be micro-optimization; at worst.

Do not worry about such ideas.

If you are not going to change the value, use const . And move on.

0
source

You can think of something like this:

 void foo(vector<int> large_object) 

against.

 void foo(const vector<int>& large_object) 

The second case may be faster, because the compiler will only push a link to the stack. In the first case, the entire vector will be pressed.

0
source

This probably depends on the compiler and the nature of the function, in fact there is no way for optimization. If you are thinking about the compiler task, when you choose when to use the CPU registers and which boot command to use, I cannot find any use cases when knowing that the const parameter will allow the compiler to optimize the code.

However, you should use const in your function declarations. He himself documents and lets others know the nature of the parameters. Also, this may 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! } 
-one
source

All Articles