I know one of the advantages of std::stringstream is that it is a std::istream so it may accept input from any type that defines operator<< to std::istream, and also from primitives types.
I am not going to use operator<<; instead I am just going to concatenate many strings. Does the implementation of std::stringstream make it faster than std::string for concatenating many strings?
There’s no reason to expect
std::string‘s appending functions to be slower thanstringstream‘s insertion functions.std::stringwill generally be nothing more than a possible memory allocation/copy plus copying of the data into the memory.stringstreamhas to deal with things like locales, etc, even for basicwritecalls.Also,
std::stringprovides ways to minimize or eliminate anything but the first memory allocation. If youreservesufficient space, every insertion is little more than amemcpy. That’s not really possible withstringstream.Even if it were faster than
std::string‘s appending functions, you still have to copy the string out of thestringstreamto do something with it. So that’s another allocation + copy, which you won’t need withstd::string. Though at least C++20 looks set to remove that particular need.You should use
std::stringstreamif you need formatting, not just for sticking some strings together.