C-Style strings versus library string performance
<h1>Question</h1>

<p>Is it true that C-style strings operations, on average, execute 5 times slower than library <code>string</code> class operations, as C++ Primer, 4th Edition would have me believe?</p>

<h2>Why ask?</h2>

<p>Because when I actually performance test, it turns out that C-style strings are about 50% faster for a particular example (one used in the book).</p>

<hr>

<h1>Setup</h1>

<p>I am reading <a href="http://rads.stackoverflow.com/amzn/click/0201721481" rel="nofollow">C++ Primer, 4th Edition</a>, which (on page 138) lists this code:</p>

<pre><code>//  C-style character string implementation
const char *pc = "a very long literal string";
const size_t  len = strlen(pc +1);    //  space to allocate

//  performance test on string allocation and copy
for (size_t ix = 0; ix != 1000000; ++ix) {
    char *pc2 = new char[len + 1];  //  allocate the space
    strcpy(pc2, pc);                //  do the copy
    if (strcmp(pc2, pc))            //  use the new string
        ;    //  do nothing
    delete [] pc2;                  //  free the memory
}

//  string implementation
string str("a very long literal string");

//  performance test on string allocation and copy
for(int ix = 0; ix != 1000000; ++ix) {
    string str2 = str;  //  do the copy, automatically allocated
    if (str != str2)    //  use the new string
        ;   //  do nothing
}    //  str2 is automatically freed
</code></pre>

<p>Now bear in mind that <strong>I'm aware of</strong> that <code>strlen(pc +1)</code> on line 2, and that the first <code>for</code> uses <code>size_t</code> but doesn't subscript the array so it might as well have been <code>int</code>, but this is exactly how it is written down in the book.</p>

<p>When I test this code (with <code>strlen(pc) + 1</code>, which I presume was intended), my results are that the first block executes about <strong>50% faster</strong> than the second block, which leads to conclusion that <strong>C-style strings are faster than library string class for this particular example</strong>.</p>

<p>However, I bet I'm missing something (probably obvious), because of what is written in the book (page 139) relating to the code above:</p>

<blockquote>
  <p>As it happens, on average, the string class implementation executes
  considerably faster than the C-style string functions. The relative
  average execution times on our more than five-year-old PC are as
  follows:</p>
</blockquote>

<pre><code> user    0.47  # string class 
 user    2.55  # C-style character string
</code></pre>

<p>So which one is it? Should I have used a longer string literal? Maybe it was because they used the GNU C Compiler and I used the Microsoft one? Is it because I have a faster computer?</p>

<p>Or is the book just wrong on this one?</p>

<h3>Edit</h3>

<p>Microsoft (R) 32-bit C/C++ Optimizing Compiler version 16.00.40219.01 for 80x86</p>
