10

Do anyone know if there is a STL interface compatible string class that allocates memory for small strings on the stack (up to a certain threshold) and the heap for larger strings ?

I'm looking to optimize a program and I'm using allot of small local strings that easily could fit on the stack, instead of being allocated on the heap.

ROAR
  • 1,304
  • 1
  • 11
  • 28
  • 2
    Visual Studio has this optimization (for very small string, just a couple characters) while gcc preferred the Copy-On-Write. – Matthieu M. Mar 24 '11 at 12:50
  • We use Visual Studio 2010 , is there anywhere you can read about this optimization (MSDN or elsewhere) ? – ROAR Mar 24 '11 at 12:59
  • 1
    Most compilers will do that, if you have a recent enough version. – Bo Persson Mar 24 '11 at 13:02
  • Looked it up and it appears to be 16 bytes in VS 2010 , no option to set it to anything else. – ROAR Mar 24 '11 at 13:21

4 Answers4

2

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.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
2

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.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 4
    Some implementation of std::string do this, it's called the small string optimisation. A quick google should tell you if yours does or if there is an alternative you can use. – Pete Mar 24 '11 at 12:40
1

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.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
0

__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.

ArtemGr
  • 11,684
  • 3
  • 52
  • 85