Home  >  Article  >  Backend Development  >  Want Speed? Pass By Value: Is Copy Elision Always the Performance Winner?

Want Speed? Pass By Value: Is Copy Elision Always the Performance Winner?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 11:59:03949browse

 Want Speed? Pass By Value: Is Copy Elision Always the Performance Winner?

Want Speed? Pass By Value: Performance Considerations

The principle of "Want speed? Pass by value" suggests that passing arguments by value can sometimes enhance performance due to copy elision. To illustrate, consider the following code using classes X and Y:

<code class="cpp">struct X {
  std::string mem_name;
  X(std::string name) : mem_name(std::move(name)) {}
};

struct Y {
  std::string mem_name;
  Y(const std::string &name) : mem_name(name) {}
};

int main() {
  X(foo());
  Y(foo());
}</code>

Here, foo() returns a temporary string that is passed to both X and Y constructors. When X initializes mem_name, it invokes the move constructor of std::string, which potentially avoids copying the string. However, when Y initializes mem_name, it must copy the string reference.

Lvalue vs Rvalue Arguments:

If an lvalue (non-temporary) is passed, both X and Y will perform a copy. Additionally, X will perform a move. For rvalues (temporaries), X may only perform a move, while Y must still perform a copy.

Performance Implications:

Generally, a move is faster than passing a pointer (equivalent to passing by reference). Therefore, X has similar performance to Y for lvalues and better performance for rvalues.

Caution:

While "Want speed? Pass by value" is a compelling idea, it should be applied judiciously. It is essential to consider the specific context and potential overhead associated with copying large data structures. Profiling is recommended to determine the actual performance impact.

Additional Resources:

  • [Scott Meyer's GN13 Talk](https://www.youtube.com/watch?v=uk3-zmJWt-E) (time-frames 8:10 and 8:56)
  • [juanchopanza's Blog: "Want Speed? Don't (Always) Pass By Value"]

The above is the detailed content of Want Speed? Pass By Value: Is Copy Elision Always the Performance Winner?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn