Hello everyone, this question has been bugging me for a while, so i thought i'd ask.
Is there a case where pass-by-reference is more expensive than pass-by-value in C++? If so, what would that case be?
Thanks.
Hello everyone, this question has been bugging me for a while, so i thought i'd ask.
Is there a case where pass-by-reference is more expensive than pass-by-value in C++? If so, what would that case be?
Thanks.
Yes, accessing a passed by reference argument might require more levels of indirection than a passed by value argument. Besides, it's may to be slower if the size of the argument is smaller than the size of a single pointer. Of course, it's all assuming the compiler is not optimizing it.
Prefer passing primitive types (int, char, float, ...) and POD structs that are cheap to copy (Point, complex) by value.
This will be more efficient than the indirection required when passing by reference.
See Boost's Call Traits.
The template class
call_traits<T>
encapsulates the "best" method to pass a parameter of some type T to or from a function, and consists of a collection of typedefs defined as in the table below. The purpose ofcall_traits
is to ensure that problems like "references to references" never occur, and that parameters are passed in the most efficient manner possible.
You can read this article "Want speed ? Pass by value" about copy elision and RVO ( Return by Value Optimization ). It explains that references sometimes prevent the compiler from doing them.
The compiler could optimize passing a primitive type by reference to simply passing by value, if the type is the same size or smaller than the size of a reference/pointer. There's no guarantee the compiler will do this, so if you have a choice, pass primitive types by value. In templated code though, you often have to pass by reference anyway - consider vector's push_back which takes a const reference. If you have a vector of ints, you'd be passing a reference to a primitive type. In that situation, you'd hope the compiler would optimise that by substituting the reference with a value. Since the vector could be storing large types though, accepting a const reference is the best choice.