When should I use string instead of stringstream?

Lucas Lima picture Lucas Lima · Aug 25, 2012 · Viewed 24.2k times · Source

When should I use stringstream instead of string::append()? Supposing I'm going to catenate just strings.

stringstream ss;
ss << str1 << "str2" << ...
Write(ss.str());

Or:

string str;
str.reserve(10000);
str.append(str1);
str.append("str2");
...
Write(str);

Which of them is faster?

Answer

Praetorian picture Praetorian · Aug 25, 2012

I don't know which one will be faster, but if I had to guess I'd say your second example is, especially since you've called the reserve member function to allocate a large space for expansion.

If you're only concatenating strings use string::append (or string::operator+=).

If you're going to convert numbers to their string representation, as well as format them during conversion, and then append the conversion results together, use stringstreams. I mention the formatting part explicitly because if you do not require formatting C++11 offers std::to_string which can be used to convert numeric types to strings.