C++ – Is Passing Arguments as Const References Premature Optimization?

cc++11optimization

"Premature optimization is the root of all evil"

I think this we can all agree upon. And I try very hard to avoid doing that.

But recently I have been wondering about the practice of passing parameters by const Reference instead of by Value. I have been taught / learned that non-trivial function arguments (i.e. most non-primitive types) should preferably be passed by const reference – quite a few books I've read recommend this as a "best practice".

Still I cannot help but wonder: Modern compilers and new language features can work wonders, so the knowledge I have learned may very well be outdated, and I never actually bothered to profile if there are any performance differences between

void fooByValue(SomeDataStruct data);   

and

void fooByReference(const SomeDataStruct& data);

Is the practice that I have learned – passing const references (by default for non-trivial types) – premature optimization?

Best Answer

"Premature optimisation" is not about using optimisations early. It is about optimising before the problem is understood, before the runtime is understood, and often making code less readable and less maintainable for dubious results.

Using "const&" instead of passing an object by value is a well-understood optimisation, with well-understood effects on runtime, with practically no effort, and without any bad effects on readability and maintainability. It actually improves both, because it tells me that a call will not modify the object passed in. So adding "const&" right when you write the code is NOT PREMATURE.

Related Topic