"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>
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):
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!