Should I preallocate std::stringstream?

后端 未结 4 810
终归单人心
终归单人心 2020-12-16 10:39

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

4条回答
  •  臣服心动
    2020-12-16 11:27

    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.

提交回复
热议问题