In context of c++ stl library what performs better string::+= or sstream::<< or it depends upon something else?
EDIT: Does it depend on the size of data we are appending?
It depends on many various parameters, the main parameter is the implementation of these operators and compiler itself.
Just a simple test in a specific version of a compiler can be a naive observation. For example simply adding a short string 10,000,000 times to a string or istringstream and measuring the time is done here. It shows += is faster that <<.
time (ms):534.02 // For +=
time (ms):927.578 // For <<
In your real application, you should use +=, if you suspect it's slow and damaging your performance then test another one. Profiling is the keyword.
sstream::write, though, because that's what does naked string concatenation.In addition for string+= recommendation I would add that if you append plain char* and know the length of it you should use string.append(data*, length) method which will save you internal length calculation. Example for mixed C/C++ code instead of
char temp[256];
sprintf(temp, <some insane pattern>, <some valuable data>,...);
str += temp;
you should use
char temp[256];
const int length = sprintf(temp, <some insane pattern>, <some valuable data>,...);
str.apeend(temp, length);
EDIT: It is recommend to use string::+= in general and sstream::<< when you know your append strings are huge.
sstream which says it implemented like linked-list?ostringstream implemented as a linked list. I've never seen this, and it doesn't make sense.stringstream be faster than plain concatenation for big strings?
string::reservebefore going into whatever is doing the +=. For a one time thing, I'd probably use+=, but in a loop I'd try to do something smarter.