When passing primitive types like int or float, is it wasted effort to write something like this:
foo(const float&);
rather than just passing by value:
foo(float);
When passing primitive types like int or float, is it wasted effort to write something like this:
foo(const float&);
rather than just passing by value:
foo(float);
For floats? Yes, pretty much.
There's simply nothing to gain here: floats are small and the copy will not be slower than the creation of a pointer to implement the reference.
It depends on the implementation of references. As per Standard (§8.3.2/4):
It is unspecified whether or not a reference requires storage (3.7).
references could, theoretically, save you from the copy of the float
. That, of course, will be vain if references are implemented as pointers. Therefore the answer is implementation dependent.
Most of the time this kind of micro-optimizations don't make much sense. I highly doubt the bottle neck of your application is in the copy of that float
.
Keep in mind that pass-by-value may in some cases enable a broader spectrum of compiler optimizations. Chandler Carruth (of Clang fame) spoke on some of the difficulties optimizing compilers face when dealing with references/pointers to objects in his keynote at C++ Now 2013.
When passing primitive types like float, it doesn't help anything to pass by const reference. Passing by value accomplishes pretty much the same thing - any change made to the value of the parameter will not affect the value in the calling function (if calling by value) - no change can be made to the parameter (if calling by const reference).
With classes, however, passing a const class reference would be much more efficient than passing it by value (which would have to make a copy of the object).