stringstream 内部是如何工作的?

发布于 2024-09-30 03:57:43 字数 99 浏览 8 评论 0原文

我问的是性能方面的问题。 stringstream 是否只是一个字符串/向量,因此写入它可能会导致其整个内容被复制到更大的内存块,或者是以更棘手的方式完成的(例如,字符串列表或其他)?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妞丶爷亲个 2024-10-07 03:57:43

27.7.3/1 表示 basic_ostringstream 使用 basic_stringbuf。我认为 27.7.1.3/8 表示 basic_stringbuf 通过重新分配缓冲区来腾出空间,甚至不能保证指数增长(因此要摊销 O(1) 来追加)。

但我发现标准的流部分非常难以理解,并且总是存在“假设”规则。因此,我不能向您保证,实际上禁止在下面使用deque(并在有人请求字符串/缓冲区时进行合并)。

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.

单挑你×的.吻 2024-10-07 03:57:43

如何实现 stringstream (或任何与此相关的库功能)取决于标准库供应商。您可以查看编译器附带的 sstream 标头,了解它是如何实现的。理论上就这么多......

根据实践经验和测量结果显示,与其他将数据格式化为字符串的方法相比,ostringstream 通常速度较慢。但话又说回来,只有在你测量到你要优化的确实是性能瓶颈之后才进行优化,否则充其量只是浪费时间。

如果您的测量结果表明 ostringstream 的性能确实对您来说是个问题,请考虑使用 Boost.Karma。当然,使用 Boost.Karma 的原因不仅仅是性能,因此,如果您要开始编写新代码而不是想使用字符串流修改现有代码,那么您可能希望从一开始就使用 Karma。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文