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?
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.
string stream is slow. Quite very slow. If you are writing anything performance critical that acts on large data sets ( say loading assets after a level change during a game ) do not use string streams.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With