In our project there are lots of functions where strings are passed via copy:
void f(std::string a);
As we all know it's more effective to pass it by reference, but my collegue says the compiler will optimize it anyway. Is this any close to truth for GCC?
G++ 4.8.2, -O2 enabled in Release build.
Thanks!
This is a somewhat controversial issue.
In theory, yes the compiler is more likely to apply certain optimizations when passing by value. Chandler Carruth explained how this works for LLVM in his BoostCon 2013 keynote Optimizing the Emergent Structures of C++ (video)/(slides).
The problem is that there are overheads to pass-by-value which the compiler is not able to get rid of. This is true even when you have a conformant C++11 compiler and a movable type like std::string
. Herb Sutter discussed the issue of calling conventions in particular in his CppCon2014 talk Essentials of Modern C++ Style (slides). His conclusion is to do it like you learned in C++98-school: Use const&
as a default for passing non-trivial arguments.
Another big arguments against the pass-by-value convention is that it becomes very hard to write efficient code that gives a strong exception-safety guarantee: To get efficiency, the user will have to move the string into the function. But in that case, if the function throws, the string is gone forever.
Of course the prime directive of optimization still applies: When in doubt, measure. Run a profiler on your real code to see which works better for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With