0

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.

ooxi
  • 3,159
  • 2
  • 28
  • 41
  • 1
    _" but I'm afraid the compiler cannot optimize the templates way if I do that"_ Why? These are merely syntactic sugar to ensure type consistency. – πάντα ῥεῖ Jan 13 '16 at 11:49
  • 2
    Just a point in general, In case of multi threaded program, if the object you are passing is shared by/acted upon more than one thread concurrently, then passing by value or reference could have different result. – rahul.deshmukhpatil Jan 13 '16 at 11:54
  • @πάνταῥεῖ because I'm not sure whether or not a `float const&` argument is as optimized as a `float const` argument – ooxi Jan 13 '16 at 11:56
  • Thantk @rahul.deshmukhpatil I updated my question – ooxi Jan 13 '16 at 11:58
  • "*if I accept const& the compiler has to at least emit double code in the case I'm invoking from a multithreaded enviroment*" Huh?! – David Schwartz Jan 13 '16 at 12:00
  • You have to make a decision based on the difference between the cost of copying the object (expensive for things like `string` and `vector`) and the cost of the compiler not being able to apply optimisations because it's assuming the reference is aliased somewhere else. – Simple Jan 13 '16 at 12:01
  • Possible duplicate of http://stackoverflow.com/questions/34712560/c-copied-and-direct-function-parameters/34712694#34712694 – Danny_ds Jan 13 '16 at 13:56

1 Answers1

1

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148