"Want Speed? Pass by Value" and Performance Optimization
When dealing with copy-heavy operations, developers often strive to optimize performance. This premise has led to the axiom "Want speed? Pass by value" coined by Scott Meyers. However, this notion raises the question: does passing by value always provide a performance advantage over passing by reference?
Considering the following 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) {} };</code>
In X, the constructor takes a copy of the argument and uses the move constructor to initialize its member variable mem_name. In Y, the constructor takes a const reference and initializes mem_name directly from the argument.
Now, let's examine a scenario where we utilize these classes:
<code class="cpp">std::string foo() { return "a" + std::string("b"); } int main() { X(foo()); Y(foo()); }</code>
Function foo() returns a temporary value used to initialize name in X and mem_name in Y.
In the case of X, the compiler can optimize the construction of foo() and place its return value directly into name. Afterward, it moves name into mem_name. This process results in a single move, without any copy.
In contrast, Y cannot perform this optimization. It binds the temporary return value of foo() to its reference name and then copies that value into mem_name. Therefore, Y performs a copy.
In summary, when passing an rvalue (temporary object), passing by value in X has the potential to optimize the process to a single move, while passing by reference in Y requires a copy. However, it's important to note that this optimization depends on compiler capabilities, and profiling is always advisable to determine the actual performance impact.
The above is the detailed content of Is \'Want Speed? Pass by Value\' Always True: When Does Passing by Reference Outperform Passing by Value?. For more information, please follow other related articles on the PHP Chinese website!