我应该预分配std :: stringstream? [英] Should I preallocate std::stringstream?

查看:339
本文介绍了我应该预分配std :: stringstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 std :: stringstream 广泛地在我的应用程序中构造字符串和错误消息。 stringstreams 通常是非常短的生命自动变量。



这样的使用会导致每个变量的堆重新分配吗?我应该从临时切换到类成员 stringstream 变量吗?



在后一种情况下, c $ c> stringstream 缓冲区? (我应该用足够大的字符串初始化它还是有更优雅的方法?)

解决方案

并发现它们是减速的来源?



考虑它们的用法。



至于预留空间...



一些实现可能在对stringstream进行任何分配之前保留一个小缓冲区。 std :: string的许多实现都会执行此操作。



另一个选项可能是(未测试!)

  std :: string str; 
str.reserve(50);
std :: stringstream sstr(str);

您可能会在 gamedev线程



edit: p>

使用 stringstream的rdbuf 进行处理也可能是一个解决方案。这种方法可能很容易弄错,请确保绝对必要 。绝对不优雅或简洁。


I use std::stringstream extensively to construct strings and error messages in my application. The stringstreams are usually very short life automatic variables.

Will such usage cause heap reallocation for every variable? Should I switch from temporary to class-member stringstream variable?

In latter case, how can I reserve stringstream buffer? (Should I initialize it with a large enough string or is there a more elegant method?)

解决方案

Have you profiled your execution, and found them to be a source of slow down?

Consider their usage. Are they mostly for error messages outside the normal flow of your code?

As far as reserving space...

Some implementations probably reserve a small buffer before any allocation takes place for the stringstream. Many implementations of std::string do this.

Another option might be (untested!)

std::string str;
str.reserve(50);
std::stringstream sstr(str);

You might find some more ideas in this gamedev thread.

edit:

Mucking around with the stringstream's rdbuf might also be a solution. This approach is probably Very Easy To Get Wrong though, so please be sure it's absolutely necessary. Definitely not elegant or concise.

这篇关于我应该预分配std :: stringstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆