Home > Backend Development > C++ > body text

Passing by Value or Reference: When is \'Want Speed? Pass by Value\' Actually True?

Susan Sarandon
Release: 2024-10-27 01:34:03
Original
447 people have browsed it

  Passing by Value or Reference: When is

"Want Speed? Pass by Value" - Exploring Performance Implications

Scott Meyers' statement "Want speed? Pass by value" raises questions about the performance benefits of passing objects by value versus by reference. In this context, passing by value involves a copy operation, while passing by reference avoids unnecessary copies.

Consider the following example with structs 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) {}
};</code>
Copy after login

In X's constructor, the argument name is copied to a temporary object before invoking the move constructor on std::string to initialize mem_name. In Y's constructor, the argument name is a const reference, but a copy is still made to initialize mem_name. Therefore, X performs a "copy-then-move" operation, while Y performs a single copy.

According to Meyers' argument, it would seem that passing by value (as in X) could be faster due to the potential for optimizations, such as return value optimization (RVO). However, a closer examination reveals that the outcome depends on the type of argument being passed (lvalue or rvalue):

  • Lvalues: Both X and Y will perform a copy (in X when initializing name, in Y when initializing mem_name), followed by a move operation in X.
  • Rvalues: X may only perform a move if RVO can be applied, while Y still requires a copy.

Generally, a move is faster than passing a pointer, which is essentially what passing by reference does. Therefore, for rvalues, X performs better than Y, while for lvalues, the performance is similar.

It's important to note that this is not a universal rule and optimizations may vary depending on the compiler and platform. Profiling is recommended to determine the optimal approach in specific cases.

The above is the detailed content of Passing by Value or Reference: When is \'Want Speed? Pass by Value\' Actually True?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!