60

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?

TooTone
  • 7,129
  • 5
  • 34
  • 60
André Puel
  • 8,741
  • 9
  • 52
  • 83

1 Answers1

79

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • So what do I use if I only need to stick some strings together? I know exactly the size of the resulting string so I would like to preallocate it, but the code that sticks strings togethers requires an OStream and uses `<<` for concatenation (it works with `std::cout`, `std::cerr`, `std::stringstream`) but it doesn't work with `std::string`. Do I really need to write a small wrapper around `std::string` just for this? – gnzlbg May 10 '16 at 14:04
  • I just wrote a small wrapper around a std::string with an `operator<<` that concatenates and that worked just fine. I just reserve the final size and after concatenating I move the string out. Feels like the stone age: string has `append` and `operator+` while `streams` have `write` and `operator<<`... – gnzlbg May 10 '16 at 14:23
  • 12
    Please do add some benchmarks to support your answer. – Jaideep Shekhar Dec 08 '19 at 15:02
  • 1
    While stringstream is not inherently faster, it is easier to use in an efficient way (avoiding temporaries / dynamic memory allocations) when it comes to concatenating strings. See https://learning.oreilly.com/library/view/optimized-c/9781491922057/ch04.html (Chapter 4 of the Book "Optimized C++" by Kurt Guntheroth) – paleonix Sep 23 '20 at 00:53