1

I saw a code like following. My understanding is that it has the following perf issues:

Should use string.append rather than + operator. str1 + "abc" will cause a new string object with its underlying heap data copied from str1 and moved from "abc" (because it matches string operator + (string& lhs, string&& rhs)(. Then with additional "+" in the expression, it will create new string object total 3 times with multiple overlapping copy operations which is waste full. string.append should do in-place extension. it will neither cause creating 3 string objects, nor will it cause wasteful copy. Can someone confirm my understanding?

class Foo {
 public:
  std::string GetCombined() {
    return str1 + "abc" + str2 + "xyz";
  }

 private:
  std::string str1, str2;
}
Kenneth
  • 561
  • 1
  • 5
  • 13
  • 1
    Benchmark it and find out. – tadman Oct 21 '20 at 19:50
  • *"operator + (string& lhs, string&& rhs)"* No, there's an overload of `+` with `const char *` as the second operand. *"+ will create new ... object ... with multiple overlapping copy operations"* Nothing stops `+` from reusing the heap buffer of one of the operands if it happens to be large enough. And nothing stops `append` from doing wasteful copies, becaue the first `append` call doesn't know anything about the calls that will follow, and might not allocate enough memory for all of them. You need to use `reserve()`. And all of this might not matter if the strings are short and SSO kicks in. – HolyBlackCat Oct 21 '20 at 19:56
  • @HolyBlackCat with regard to your statement of "Nothing stops + from reusing the heap buffer of one of the operands if it happens to be large enough." In the case of str1 + "abc", compiler can reuse str1's heap buffer because it will alter the original value I assume. It seems possible to reuse the heap buffer allocated to "abc" since it is temp anyway, so the result will heap buffer of "abc" if it has enough space? – Kenneth Oct 21 '20 at 23:05
  • @Kenneth Sorry, I wasn't specific enough. Yes, `str1 + "abc"` isn't going to reuse the buffer of `str` because it's not an rvalue. But `... + str2` can reuse the bufer of the temporary string that the previous step created. And `... + "xyz"` can reuse the buffer of this new string. – HolyBlackCat Oct 22 '20 at 06:43

0 Answers0