Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is returning a const std::string really slower than non-const?

Tags:

c++

c++11

c++14

In another question a user made a comment that returning a const std::string loses move construction efficiency and is slower.

Is it really true that assigning a string of return of this method:

const std::string toJson(const std::string &someText);

const std::string jsonString = toJson(someText);

... is really slower than the non-const version:

std::string toJson(const std::string &str);

std::string jsonString = toJson(someText);

And what is the meaning of move-construction efficiency in this context?

I've never heard of that limitation before and do not remember having seen that in the profiler. But I'm curious.

Edit: There is a suggested question asking: What is move semantics?. While some of the explanations of course relate to efficiency, it explains what move semantics means, but does not address why returning a const value can have negative side effects regarding performance.

like image 276
benjist Avatar asked Oct 16 '25 08:10

benjist


1 Answers

Consider the following functions:

std::string f();
std::string const g();

There is no difference between:

std::string s1 = f();
std::string s2 = g();

We have guaranteed copy elision now, in both of these cases we're constructing directly into the resulting object. No copy, no move.

However, there is a big difference between:

std::string s3, s4;
s3 = f(); // this is move assignment
s4 = g(); // this is copy assignment

g() may be an rvalue, but it's a const rvalue. It cannot bind to the string&& argument that the move assignment operator takes, so we fall back to the copy assignment operator whose string const& parameter can happily accept an rvalue.

Copying is definitely slower than moving for types like string, where moving is constant time and copying is linear and may require allocation.

Don't return const values.


On top of that, for non-class types:

int f();
int const g();

These two are actually the same, both return int. It's an odd quirk of the language that you cannot return a const prvalue of non-class type but you can return a const prvalue of class type. Easier to just pretend you can't do the latter either, since you shouldn't.

like image 124
Barry Avatar answered Oct 19 '25 01:10

Barry