When should I use string instead of stringstream?

26,741

Solution 1

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.

Solution 2

string.append is much faster. Especially when you reserve.

If you are concatenating only strings, I would use string.append. I would only use stringstream when I need to automatically convert non-strings to strings for example:

const int x(42);
stringstream ss;
ss << "My favorite number is: " << x << std::endl;

Here stringstream automatically converts x to a string and appends it. I do not need to call atoi. Stringstream will convert all the basic types automatically for you. It is great for that purpose.

Also if you are only going to be directing data into the stringstream to convert it to a string later. You can use ostringstream which is for output.

I hope that helps.

Share:
26,741
Lucas Lima
Author by

Lucas Lima

Updated on May 27, 2020

Comments

  • Lucas Lima
    Lucas Lima almost 4 years

    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?