3 ms·
> Given a modern compiler and library, a by-value string temporary can be passed down a chain of calls with no allocations beyond the first, and returned, likew
by comex 7y ago
> Given a modern compiler and library, a by-value string temporary can be passed down a chain of calls with no allocations beyond the first, and returned, likewise.
For calls (as opposed to returns): If you use std::move, yes. Otherwise, no. But using std::move is similar to changing the type in that it requires noticing the problem first.
> Passing a reference means the optimizer cannot optimize accesses, because it doesn't know what other pointers might be aliasing it. string_view has the same problem.
For `const std::string &`, the optimizer has to assume that the string pointer and length could change, which is indeed a problem as it has to keep reloading them if you call, e.g., `c_str()` or `size()` multiple times (with other things in between). For both `const std::string &` and `std::string_view`, the optimizer has to assume that the string data could change, but not the pointer or length, which is much less of a problem because you don't usually repeatedly load the same piece of string data in a loop. Therefore, `std::string_view` is a decent choice.
Passing `std::string` by value does indeed have the advantage that the compiler indeed could theoretically assume the string data is not aliased. But I just checked and none of Clang, GCC, MSVC, or ICC actually do so:
https://gcc.godbolt.org/z/DZPsuU https://gcc.godbolt.org/z/DZPsuU
- ncmncm 7y agoAgain, doing it wrong is Doing It Wrong. But moving can pessimize string-passing and -returning. Just write the code in the clearest way possible, and optimize hot paths where it turns out to matter, according to measurements. People have been demonstrated to be very poor at picking which those are, a priori.
- codesushi42 7y agoQuotes about Chromium and Firefox are likewise obsolete Yeah, because neither of those teams had any idea what they were doing, obviously. Even with C++ 11 at their disposal. But somehow, interestingly enough, you do. Neither uses RAII, so they pay a 20-30% runtime penalty Who knows where you pulled that number from. I guess then, according to you at least, there are no performance penalties to be paid for any C++ language features. Please, continue to impart your knowledge and unreferenced benchmark tests on us all.