std::string in VC++ may store a short string in a stack

The std::string object can store any length of string. However, it does not mean it always allocate char array on the heap.

If you look into the type definition of std::string in VC++ 8.0, it has interesting array called _Bx::_Buf.

   +0x000 _Alval           : std::allocator<char>
   =00400000 npos             : Uint4B
   +0x004 _Bx              : std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Bxty
      +0x000 _Buf             : [16] Char
      +0x000 _Ptr             : Ptr32 Char
   +0x014 _Mysize          : Uint4B
   +0x018 _Myres           : Uint4B

When the string is less than 16 characters, it actually stores it inside the std::string object. Otherwise, it dynamically allocates char array on a heap.

Here is the bench mark result of string constructor performance for various length. You can see the obvious performance hit at the 16 characters.




The source code for the bench mark is here:

using namespace std;

int main(){
    boost::timer tim;
    string a;

    for(size_t c = 0; c < 20; c++){
        for(size_t i = 0; i < 10000000; i++){
            string str = a;
        cout << c << " " << tim.elapsed() << endl;
        a += "0";

About Moto

Engineer who likes coding
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s