String class allocating on stack for small strings?

主宰稳场 提交于 2019-12-01 16:01:52
Björn Pollex

You can provide a custom allocator for std::basic_string (it is the third template argument). This answer explains how use that and links to an implementation of a stack-allocator that can be used.

The vstring (__versa_string) implementation from gcc can do the small string optimization and has a std string interface. If you happen to be using gcc it's easy enough to include ext/vstring. Otherwise you may be able to adapt it to your compiler/enviroent.

This is antique question, but I feel that this is better that any of the current answers.

http://llvm.org/docs/ProgrammersManual.html#dss_smallstring

Basically it is what you want. BTW tcmalloc increased perf in my (badly designed :D) string alloc intensive program 10%. Also you should profile to prove allocs are your perf problem.

__versa_string SSO version can store no more than 15 bytes on the stack and if it does, it reserves 16 bytes regardless of the string size ( http://codepad.org/2M7N9cTu ).

http://www.and.org/ustr/ can reuse a stack buffer, but I had problems linking with it under Debian Wheezy 64bit.

http://freecode.com/projects/str-class can reuse a stack buffer.

I wrote a header-only string class which uses just four bytes and can reuse a stack buffer: http://code.google.com/p/libglim/source/browse/trunk/gstring.hpp
It has a limited STL compatibility: basic_streambuf implemented for use with std::ostream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!