views:

52

answers:

2

I'm asking in context of performance. Is stringstream simply a string/vector, so writing to it may result in its whole content being copied to a bigger chunk of memory, or is it done in a more tricky way (say, a list of strings or whatever)?

+2  A: 

27.7.3/1 says that basic_ostringstream uses a basic_stringbuf. I think that 27.7.1.3/8 says that basic_stringbuf makes space by reallocating a buffer, and doesn't even guarantee exponential growth (and hence amortized O(1) to append).

But I find the streams section of the standard pretty impenetrable, and there's always the "as-if" rule. So I can't promise you that using a deque underneath (and consolidating when someone asks for the string / buffer) is actually forbidden.

Steve Jessop
basic_stringbuf does not have to store its memory in a contiguous format thus when its buffer is full, it will not necessary reallocate (i.e. move the original memory) but may get it to work a bit like std::deque. As STL is open-source you can look at how any particular vendor implements basic_stringbuf.
CashCow
+3  A: 

It's up to the standard library vendor how to implement stringstream (or any library feature for that matter). You can look at the sstream header shipped with your compiler to see how it's implemented there. That much on the theoretical side...

As far as practical experience and measurements show, ostringstream is often slow compared to other methods for formatting data as character strings. But then again, only optimize after you have measured that what you want to optimize is indeed a performance bottleneck, otherwise that'll just be a waste of time at best.

If your measurements show that the performance of ostringstream really is a problem for you, consider using Boost.Karma. Of course there are more reasons to use Boost.Karma than just performance, so if you are starting a new code rather than want to modify an existing one using string streams, you might well want to use Karma from the get-go.

usta
While implementations do vary, the standard does make general performance requirements in many cases. I believe that is what the OP is asking about.
Roger Pate
@Roger Pate: Sure there are complexity requirements in the standard, but I don't remember any that would prevent implementation of ostringstream using either a single contiguous buffer or multiple fixed-size buffers. In fact I personally don't remember any complexity specifications for standard i/o stream functions at all. Do you?
usta