Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#\'s StringBuilder or Java\'s StringBuffer?
I wanted to add something new because of the following:
At a first attemp I failed to beat
std::ostringstream 's operator<<
efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.
Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.
The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):
for byte [ ]
for moved strings (strings appended with std::move)
std::string object (we have ownership)for strings
std::string object (no ownership)There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)
This was finally slightly faster than std::ostringstream but it has few downsides:
ostringstreamconclusion? use
std::ostringstream
It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.