Should I preallocate std::stringstream?

jackhab picture jackhab · Dec 21, 2009 · Viewed 18.5k times · Source

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

Answer

luke picture luke · Dec 21, 2009

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.