title: How efficient is std::string compared to null-terminated strings?
body: <p>I've discovered that <code>std::string</code>s are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall program by a factor of 2.</p>
  
  <p>I expected STL to be slower, I didn't realise it was going to be this much slower.  </p>
  
  <p>I'm using Visual Studio 2008, release mode. It shows assignment of a string to be 100-1000 times slower than <code>char*</code> assignment (it's very difficult to test the run-time of a <code>char*</code> assignment).  I know it's not a fair comparison, a pointer assignment versus string copy, but my program has lots of string assignments and I'm not sure I could use the "<em>const reference</em>" trick in all places.  With a reference counting implementation my program would have been fine, but these implementations don't seem to exist anymore.</p>
  
  <p>My real question is:  why don't people use reference counting implementations anymore, and does this mean we all need to be much more careful about avoiding common performance pitfalls of std::string?</p>
  
  <p>My full code is below.  </p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;time.h&gt;
  
  using std::cout;
  
  void stop()
  {
  }
  
  int main(int argc, char* argv[])
  {
      #define LIMIT 100000000
      clock_t start;
      std::string foo1 = "Hello there buddy";
      std::string foo2 = "Hello there buddy, yeah you too";
      std::string f;
      start = clock();
      for (int i=0; i &lt; LIMIT; i++) {
          stop();
          f = foo1;
          foo1 = foo2;
          foo2 = f;
      }
      double stl = double(clock() - start) / CLOCKS\_PER\_SEC;
  
      start = clock();
      for (int i=0; i &lt; LIMIT; i++) {
          stop();
      }
      double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC;
  
      char* goo1 = "Hello there buddy";
      char* goo2 = "Hello there buddy, yeah you too";
      char *g;
      start = clock();
      for (int i=0; i &lt; LIMIT; i++) {
          stop();
          g = goo1;
          goo1 = goo2;
          goo2 = g;
      }
      double charLoop = double(clock() - start) / CLOCKS_PER_SEC;
      cout &lt;&lt; "Empty loop = " &lt;&lt; emptyLoop &lt;&lt; "\n";
      cout &lt;&lt; "char* loop = " &lt;&lt; charLoop &lt;&lt; "\n";
      cout &lt;&lt; "std::string = " &lt;&lt; stl &lt;&lt; "\n";
      cout &lt;&lt; "slowdown = " &lt;&lt; (stl - emptyLoop) / (charLoop - emptyLoop) &lt;&lt; "\n";
      std::string wait;
      std::cin &gt;&gt; wait;
      return 0;
  }
  </code></pre>