c++ std::ostringstream vs std::string::append
Posted
by
NickSoft
on Stack Overflow
See other posts from Stack Overflow
or by NickSoft
Published on 2013-11-07T19:25:26Z
Indexed on
2013/11/09
9:54 UTC
Read the original article
Hit count: 207
In all examples that use some kind of buffering I see they use stream instead of string. How is std::ostringstream and << operator different than using string.append. Which one is faster and which one uses less resourses (memory).
One difference I know is that you can output different types into output stream (like integer) rather than the limited types that string::append accepts.
Here is an example:
std::ostringstream os;
os << "Content-Type: " << contentType << ";charset=" << charset << "\r\n";
std::string header = os.str();
vs
std::string header("Content-Type: ");
header.append(contentType);
header.append(";charset=");
header.append(charset);
header.append("\r\n");
Obviously using stream is shorter, but I think append returns reference to the string so it can be written like this:
std::string header("Content-Type: ");
header.append(contentType)
.append(";charset=")
.append(charset)
.append("\r\n");
And with output stream you can do:
std::string content;
...
os << "Content-Length: " << content.length() << "\r\n";
But what about memory usage and speed? Especially when used in a big loop.
Update:
To be more clear the question is: Which one should I use and why? Is there situations when one is preferred or the other? For performance and memory ... well I think benchmark is the only way since every implementation could be different.
Update 2:
Well I don't get clear idea what should I use from the answers which means that any of them will do the job, plus vector. Cubbi
did nice benchmark with the addition of Dietmar Kühl that the biggest difference is construction of those objects. If you are looking for an answer you should check that too. I'll wait a bit more for other answers (look previous update) and if I don't get one I think I'll accept Tolga's answer because his suggestion to use vector is already done before which means vector should be less resource hungry.
© Stack Overflow or respective owner