2

Is it OK, performance-wise, to return a string from an arbitrary function in C++11? What is the preferred way of returning a string if "directly returning" it is not recommended?

AFAIK, strings in C++ are not reference-counted because the standard forbids this practice. From my (probably uninformed) point of view, this means that a string will be returned by copy-constructor, resulting in a possibly large memcpy. Is this right?

It is very straightforward and clean to define a function as string MyClass::makeString(...) instead of something like void MyClass::makeString(string & ret, ...). On the other hand, the latter approach might seem better from a performance perspective.

Hinton
  • 2,320
  • 4
  • 26
  • 32

2 Answers2

3

When you are returning a std::string from a function in which that string is declared as a local non-static variable, the compiler can aggressively optimize code so that very little or no copying is done. You should not worry about performance implications of this when it comes to strings.

Even in cases when you know for sure that there would be a lot of copying you shouldn't worry about the effect until your profiler points to the specific code as a source of inefficiency. In my experience, this happens very infrequently: in general, a lot more CPU time is wasted on algorithms of sub-par efficiency than on boilerplate issues, such as copying an extra string or two.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

If you are using C++11, yes, it's OK.

vz0
  • 32,345
  • 7
  • 44
  • 77