Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::stringstream vs std::string for concatenating many strings

I know one of the advantages of std::stringstream is that it is a std::istream so it may accept input from any type that defines operator<< to std::istream, and also from primitives types.

I am not going to use operator<<; instead I am just going to concatenate many strings. Does the implementation of std::stringstream make it faster than std::string for concatenating many strings?

like image 265
André Puel Avatar asked Feb 06 '13 23:02

André Puel


People also ask

Is string concatenation slow in C++?

Strings, C++'s std::strings are mutable, and therefore can be built through simple concatenation just as fast as through other methods.

How do you concatenate strings together?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What is std :: Stringstream?

Stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .


1 Answers

There's no reason to expect std::string's appending functions to be slower than stringstream's insertion functions. std::string will generally be nothing more than a possible memory allocation/copy plus copying of the data into the memory. stringstream has to deal with things like locales, etc, even for basic write calls.

Also, std::string provides ways to minimize or eliminate anything but the first memory allocation. If you reserve sufficient space, every insertion is little more than a memcpy. That's not really possible with stringstream.

Even if it were faster than std::string's appending functions, you still have to copy the string out of the stringstream to do something with it. So that's another allocation + copy, which you won't need with std::string. Though at least C++20 looks set to remove that particular need.

You should use std::stringstream if you need formatting, not just for sticking some strings together.

like image 141
Nicol Bolas Avatar answered Oct 02 '22 12:10

Nicol Bolas