Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use string instead of stringstream?

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?

like image 215
Lucas Lima Avatar asked Aug 25 '12 03:08

Lucas Lima


People also ask

What is the difference between string and Stringstream?

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.

Is Stringstream a string?

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.

Why do we use string streams?

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.

Is Stringstream slow?

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.


1 Answers

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.

like image 54
Praetorian Avatar answered Sep 20 '22 07:09

Praetorian