0

Possible Duplicate:
Pass by reference more expensive than pass by value

I want to know which is better, sending parameters by value or by reference in C++. I heard that there are cases where sending by value is faster than sending by reference. Which are these cases?

Thanks

Community
  • 1
  • 1
Jacob Krieg
  • 2,834
  • 15
  • 68
  • 140
  • When you send by value - copy of object is created (time and space consuming). So instead it is better to send by const& or &(in case if you want modify the object) – spin_eight Nov 08 '12 at 09:34
  • @UmNyobe Maybe here [Want Speed? Pass by Value.](http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/). But there is also a discussion here: http://stackoverflow.com/questions/2108084/pass-by-reference-more-expensive-than-pass-by-value – RedX Nov 08 '12 at 09:36
  • A reference is implemented using a pointer, so if the parameter is smaller than a pointer then passing it by value may be faster. – Barmar Nov 08 '12 at 09:36
  • yes, but there are cases for basic types, for example int or float where it is slower to send by reference than by value. I'd like to know which bytes does a type to have in order to be faster sending by value than reference – Jacob Krieg Nov 08 '12 at 09:37
  • "I'd like to know which bytes does a type to have in order to be faster sending by value than reference". Depends more on : which assembly instructions are used to make the value available to the function and to access this value. – UmNyobe Nov 08 '12 at 09:47

2 Answers2

1

The obvious case is when the parameter is equal to or smaller than a pointer in size and trivial to copy -- then you would pass by value. However, this is a age-old discussion and quite a long answer is required to answer it correctly for a given architecture. There are also many corner cases (e.g. RVO).

There's more to the question than speed -- semantics should be your first priority.

See also: Is it better in C++ to pass by value or pass by constant reference?

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
1

As a general rule, you should pass POD types by value and complex types by const reference.

That said, a good place where you pass complex types by value is where you would need a copy of the object inside the function anyway. In that case, you have two choices:

  • pass the argument as a const reference and create a local copy inside the function

  • pass the argument by value (the compiler creates the local copy).

The second option is generally more efficient. For an example, see the copy&swap idiom.

Community
  • 1
  • 1
utnapistim
  • 26,809
  • 3
  • 46
  • 82