"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:
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) {}
};
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3