ooxi
ooxi

Reputation: 3329

Performance of passing argument as value vs as const reference

Does it matter whether or not I pass a small object by const value or const reference on a mondern compiler? For example I have a couple of methods accepting and not modifying boost::units::quantity<boost::units::si::length, float> which should be optimized to float anyway.

Normally I would declare the argument's type as a const reference but I'm afraid the compiler cannot optimize the templates way if I do that.

Edit: what I didn't think of but was mentioned by rahul.deshmukhpatil in the comments, if I accept const& the compiler has to at least emit double code in the case I'm invoking from a multithreaded enviroment.

Upvotes: 0

Views: 173

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

If it's a POD, I would expect that passing it by value will result in slightly faster overall performance. By "slightly" I mean "only someone in a certain, specific, line of work where sanity has less priority than every nanosecond of performance, would care".

To understand why, it is necessary to understand how, on traditional hardware, functions calls are made, and arguments get passed.

Beyond PODs, the only answer would be to try either way, and gather some statistics.

And if you really do not care about a few nanoseconds' worth of difference, do what is more convenient for you.

And, in either case, templates are irrelevant.

Upvotes: 1

Related Questions