Performance of std :: string + operator versus string stream

I am migrating an old code base with a custom string implementation to use std :: string. One of our engineers is concerned that this could lead to a performance problem when we use + = and + to concatenate relatively long strings. His particular concern is how memory is allocated as the string grows dynamically, and he assumed that a string stream would perform better in this regard. For those of you who have been tempted to answer "benchmark, then optimize" or feelings for this effect, I certainly agree with this plan. I'm just interested in theory.

I did a little googling about this issue and came across this question: Effective string concatenation in C ++ , which is a little outdated.

Now I'm wondering: Is the memory allocation algorithm for string + = really different from the string stream of strings? How about the copy issues raised in the above question - have they changed with C ++ 11/14?

+3


source to share


1 answer


Is the memory allocation algorithm for string + = really different from string for stream of strings?

Yes.

The string stream writes to stringbuffer, which usually means a linked list of buffers. Memory is not contiguous and does not need to be reallocated as the buffer grows.



On the other hand, a row allocates memory in one block (as needed and sometimes preemptively).

The most efficient solution is probably to precompile the resulting string size, manually isolate the result, and fill it in (using std::string::operator +=

).

However, I'll just write to std :: ostringstream and grab the result at the end (but YMMV).

+1


source







All Articles