Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

C++ String Performance


Teststring7.cpp and teststring8.cpp, both available electronically, test the fastest mode (Mode 1: no heap allocation or copying, just setting a pointer). Example 5(a) is the result for teststring7, and 5(b) for teststring8. As expected, it's blazingly fast. Table 1 summarizes the performance test results.


(a)
Thread <1024>: Creating/destroying 100000 strings...
Thread <1024>: total time=3 millisecs, average=0.000030

(b)
Thread <1026>: Creating/destroying 100000 strings...
Thread <1026>: total time=3 millisecs, average=0.000030
Thread <3076>: Creating/destroying 100000 strings...
Thread <3076>: total time=4 millisecs, average=0.000040
Thread <4101>: Creating/destroying 100000 strings...
Thread <4101>: total time=3 millisecs, average=0.000030
Thread <5126>: Creating/destroying 100000 strings...
Thread <5126>: total time=3 millisecs, average=0.000030
Thread <6151>: Creating/destroying 100000 strings...
Thread <6151>: total time=3 millisecs, average=0.000030
Thread <7176>: Creating/destroying 100000 strings...
Thread <7176>: total time=3 millisecs, average=0.000030
Thread <8201>: Creating/destroying 100000 strings...
Thread <8201>: total time=4 millisecs, average=0.000040
Thread <9226>: Creating/destroying 100000 strings...
Thread <9226>: total time=3 millisecs, average=0.000030
Thread <10251>: Creating/destroying 100000 strings...
Thread <10251>: total time=4 millisecs, average=0.000040
Thread <2051>: Creating/destroying 100000 strings...
Thread <2051>: total time=3 millisecs, average=0.000030

Example 5: (a) The results of running teststring7.cpp; (b) results of running teststring8.cpp.

Table 1: Performance test results.

Mode 1 (fastest) is 35 times faster than std::string in a one-thread application and 2500(!) times faster for the application with just 10 threads. A no-frills Mode 3 string with heap allocation and copying is still 100 times faster than std::string for a 10-thread application thanks to the absence of the reference counting/COW optimization.

Real-World Example

In the real world, many C++ applications get their input from C network protocols or database drivers. In the case of strings, one popular use is as keys in the STL map. Listing Five does exactly that—it accepts parameters as C strings, converts them to C++ strings, and uses them as keys for the STL map. Now take a closer look at the function calls ci=m_mymap.find(str); and m_mymap.erase (str);.

Listing Five looks benign until you realize that every time you do a lookup or erase, you create a temporary string object (with heap allocation and value copying). This temporary string object is created through the std::string(char*) constructor. This object's lifespan is just the duration of the map::find/erase call: It's destroyed right before return (with another heap hit, of course). It sounds expensive—and it is. So what can you do? The first solution may be to use pointers to the strings instead of the strings themselves. It would solve a creation-of-objects problem, but burdens you with memory management and comparison issues (remember a map is a balanced tree that always keeps its contents sorted).

Listing Five

class CMyMap
{
private:
  map < string, int > m_mymap;
public:
  void add ( const char *str, int i )
  {
    m_mymap[str] = i;
  }
  void remove ( const char *str )
  {
    m_mymap.erase ( str );
  }
  bool find ( const char *str, int *res )
  {
    map < string, int >::const_iterator ci;
    ci = m_mymap.find(str);
    bool found = ( ci != m_mymap.end() );
    if ( found )
       *res = ci->second;
    return found;
  }
};

The preferred solution would be to have all the beauty of using C++ string objects as keys, but with the C speed of conversion between C strings and C++ strings for the temporary strings. That's where my new Mode 1 (FAST_STRING) shines. To achieve the speed of temporary C strings and still be able to use C++ strings for the lookup, take a look at Listing Six and testmap.cpp (available electronically). Mode 3 (value allocated on the heap) is used only when the new element is added. For the lookup and erase, the fastest Mode 1 strings are used (just setting the pointer).

Listing Six

class CMyMap
{
private:
  map < CGenString, int > m_mymap;
  typedef map < CGenString, int > GenStringIntMap;
public:
  void add ( const char *str, int i )
  {
    m_mymap[str] = i;
  }
  void remove ( const char *str )
  {
    FAST_STRING(s,str);
    m_mymap.erase ( s );
  }
  bool find ( const char *str, int *res )
  {
    map < CGenString, int >::const_iterator ci;
    FAST_STRING(s,str);
    ci = m_mymap.find(s);
    bool found = ( ci != m_mymap.end() );
    if ( found )
      *res = ci->second;
    return found;
  }
};



There is no allocation and no copying, which means that you have a real automatic (stack) string variable with all the performance of C strings and all power/convenience of the STL map. The constructor and destructor are extremely simple for the fastest (Mode 1) strings—just setting a pointer in the constructor, and no-op in the destructor.

Possible Improvements

One area of improvement would be adding support for multibyte characters. A good way to do this would be to follow STL string design (where string is typedefed to basic_string <char>) and add another template parameter for the actual character type.


Lev is a principal engineer at Netscape/AOL and can be contacted at [email protected] or [email protected].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.