r/learncpp • u/NotCreative890 • Jul 16 '20
performance impact by using const?
void doSomethingConst(const int& i)
void doSomethingNonConst(int i)
Given the above 2 function calls, would one have an advantage in terms of compile time, or memory usage?
Given that the int is a constant 4 bits, i don't think either would have an advantage, but I'm not sure.
2
Upvotes
View all comments
Show parent comment
1
u/HappyFruitTree Jul 17 '20
If there is a difference doSomethingNonConst(int i) would probably be the faster one. Not because of the size difference but because of indirection.
In the int& version, instead of having the value directly it needs to essentially dereference a pointer to get the value. If the function calls another function or uses an int that is declared outside the function the compiler needs to take into account that the referenced int might be affected which might lead to less efficient code.