Converting std::string to upper case: major performance difference?
<p>So I was playing around with some code and wanted to see which method of converting a std::string to upper case was most efficient.  I figured that the two would be somewhat similar performance-wise, but I was terribly wrong.  Now I'd like to find out why.</p>

<p>The first method of converting the string works as follows: for each character in the string (save the length, iterate from 0 to length), if it's between 'a' and 'z', then shift it so that it's between 'A' and 'Z' instead.</p>

<p>The second method works as follows: for each character in the string (start from 0, keep going till we hit a null terminator), apply the build in toupper() function.</p>

<p>Here's the code:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;

inline std::string ToUpper_Reg(std::string str)
{
    for (int pos = 0, sz = str.length(); pos &lt; sz; ++pos)
    {
        if (str[pos] &gt;= 'a' &amp;&amp; str[pos] &lt;= 'z') { str[pos] += ('A' - 'a'); }
    }

    return str;
}

inline std::string ToUpper_Alt(std::string str)
{
    for (int pos = 0; str[pos] != '\0'; ++pos) { str[pos] = toupper(str[pos]); }

    return str;
}


int main()
{
    std::string test = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&amp;*()_+=-`'{}[]\\|\";:&lt;&gt;,./?";

    for (size_t i = 0; i &lt; 100000000; ++i) { ToUpper_Reg(test); /* ToUpper_Alt(test); */ }

    return 0;
}
</code></pre>

<p>The first method <code>ToUpper_Reg</code> took about <strong>169 seconds</strong> per 100 million iterations.<br>
The second method <code>Toupper_Alt</code> took about <strong>379 seconds</strong> per 100 million iterations.</p>

<p>What gives?</p>

<hr>

<p><em>Edit:</em> I changed the second method so that it iterates the string how the first one does (set the length aside, loop while less than length) and it's a bit faster, but still about twice as slow.</p>

<hr>

<p><em>Edit 2:</em> Thanks everybody for your submissions!  The data I'll be using it on is guaranteed to be ascii, so I think I'll be sticking with the first method for the time being.  I'll keep in mind that <code>toupper</code> is locale specific for when/if I need it.</p>
