How does stringstream work internally?

喜你入骨 提交于 2019-12-19 03:15:50

问题


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)?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4063396/how-does-stringstream-work-internally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!