我要问的是性能问题.字符串流是简单的字符串/向量,因此对其进行写入可能会导致其整个内容被复制到更大的内存块中,还是以更为棘手的方式(例如,字符串列表或其他方式)完成了?
解决方案由标准库供应商决定如何实现字符串流(或任何与此相关的库功能).您可以查看编译器随附的sstream标头,以了解如何在其中实现它.从理论上讲……
据实践经验和测量结果显示,与其他将数据格式化为字符串的方法相比,ostringstream的速度通常较慢.但是话又说回来,只有在您确定要优化的确是性能瓶颈之后再进行优化,否则充其量只是在浪费时间.
如果您的测量结果表明ostringstream的性能确实对您有问题,请考虑使用 Boost.Karma .当然,使用Boost.Karma的原因不仅仅是性能,还有更多原因,因此,如果您要开始新代码而不是想要使用字符串流修改现有代码,则很可能一开始就想使用Karma.
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)?
解决方案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.
更多推荐
stringstream在内部如何工作?
发布评论