0

I am just curious about the implementation of c++ string +=.

Is there any performance penalty for this? Which one is supposed to be faster?

String a = "xxx";
a += "(" + "abcd" + ")"

or

String a = "xxx";
a.append("(");
a.append("abcd");
a.append(")");
WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30
  • 2
    Have a look at this: [Efficient string concatenation in C++][1] [1]: http://stackoverflow.com/questions/611263/efficient-string-concatenation-in-c It explains it very well.:) – Spyros Nov 28 '12 at 03:22
  • 1
    @SpyrosR: It does explain it well, but for a different operator. – NPE Nov 28 '12 at 06:55
  • THanks! Actually my question is not well described... I changed it now and found the answer from what @SpyrosR posted. – WhatABeautifulWorld Nov 28 '12 at 17:49

3 Answers3

2

Given that they have word-for-word identical specs in the standard, it's hard to envisage a reasonable implementation where their runtime cost would differ:

21.4.6 basic_string modifiers [string.modifiers]

21.4.6.1 basic_string::operator+= [string::op+=]

basic_string& operator+=(const basic_string& str);

1 Effects: Calls append(str.data, str.size()).

2 Returns: *this

...

21.4.6.2 basic_string::append [string::append]

basic_string& append(const basic_string& str);

1 Effects: Calls append(str.data(), str.size()).

2 Returns: *this.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

I'd be very surprised if the += operator wasn't implemented by a call to append.

In fact, SGI's documentation for basic_string indicates that:

basic_string& operator+=(const basic_string& s) Equivalent to append(s).

Furthermore, the code reads:

basic_string& operator+=(const basic_string& __s) { return append(__s); }

http://www.sgi.com/tech/stl/string

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • The C++ stdlib is no direct copy of SGI's interface. Better use http://en.cppreference.com/w/cpp/string/basic_string/operator%2B%3D as reference, which tells basically the same. – Kijewski Feb 27 '13 at 03:08
0

There are no difference between them, In fact += operator's implemention just invoke append. I read it from the STL code.

Healer
  • 290
  • 1
  • 7