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

5
  • 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) Commented Nov 8, 2012 at 9:34
  • @UmNyobe Maybe here Want Speed? Pass by Value.. But there is also a discussion here: stackoverflow.com/questions/2108084/… Commented Nov 8, 2012 at 9: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. Commented Nov 8, 2012 at 9: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 Commented Nov 8, 2012 at 9: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. Commented Nov 8, 2012 at 9:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.