<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[The ryg blog]]></provider_name><provider_url><![CDATA[https://fgiesen.wordpress.com]]></provider_url><author_name><![CDATA[fgiesen]]></author_name><author_url><![CDATA[https://fgiesen.wordpress.com/author/fgiesen/]]></author_url><title><![CDATA[A string processing&nbsp;rant]]></title><type><![CDATA[link]]></type><html><![CDATA[<p><em>This post is part of a series &#8211; go <a href="https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/">here</a> for the index.</em></p>
<p>Rants are not usually the style of this blog, but this one I just don&#8217;t want to keep in. So if you&#8217;re curious, the actual information content of this post will be as follows: C string handling functions kinda suck. So does C++&#8217;s <code>std::string</code>. Dealing with wide character strings using only standard C/C++ functionality is absolutely horrible. And VC++&#8217;s implementation of said functionality is a damn minefield. That&#8217;s it. You will not actually learn anything more from reading this post. Continue at your own risk.</p>
<p><b>UPDATE</b>: As &#8220;cmf&#8221; points out in the comments, there are actually C++ functions that seem to do what I wanted in the first place with a minimum amount of fuss. Goes to show, the one time I post a rant on this blog and of course I&#8217;m wrong! 🙂 That said, I do stand by my criticism of the numerous API flaws I point out in this post, and as I point out in myreply, the discoverability of this solution is astonishingly low; when I ran into this problem originally, not being familiar with <code>std::wstring</code> I googled a bit and checked out Stack Overflow and several other coding sites and mailing list archives, and what appears to be the right solution showed up on none of the pages I ran into. So at the very least I&#8217;m not alone. Ah well.</p>
<h3>The backstory</h3>
<p>I spent most of last weekend playing around with <a href="https://github.com/rygorous/intel_occlusion_cull">my fork</a> of <a href="http://software.intel.com/en-us/vcsource/samples/software-occlusion-culling">Intel&#8217;s Software Occlusion Culling</a> sample. I was trying to optimize some of the hot spots, a process that involves a lot of small (or sometimes not-so-small) modifications to the code followed by a profiling run to see if they help. Now unfortunately this program, at least in its original version, had loading times of around 24 seconds on my machine, and having to wait for those 24 seconds every time before you can even start the profiling run (which takes another 10-20 seconds if you want useful results) gets old <em>fast</em>, so I decided to check whether there was a simple way to shorten the load times.</p>
<p>Since I already had the profiler set up, I decided to take a peek into the loading phase. The first big time-waste I found was a texture loader that was unnecessarily decompressing a larger DXT skybox texture, and then recompressing it again. I won&#8217;t go into details here; suffice it to say that once I had identified the problem, it was straightforward enough to fix, and it cut down loading time to about 12 seconds.</p>
<p>My next profiling run showed me this:</p>
<p><a href="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png"><img loading="lazy" data-attachment-id="1314" data-permalink="https://fgiesen.wordpress.com/2013/01/30/a-string-processing-rant/hotspots_loading/" data-orig-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png" data-orig-size="497,342" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Loading hotspots" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?w=497" src="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?w=497&#038;h=342" alt="Loading hotspots" width="497" height="342" class="aligncenter size-full wp-image-1314" srcset="https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png 497w, https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?w=150&amp;h=103 150w, https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?w=300&amp;h=206 300w" sizes="(max-width: 497px) 100vw, 497px" /></a></p>
<p>I&#8217;ve put a red dot next to functions that are called either directly or indirectly by the configuration-file class <code>CPUTConfigFile</code>. Makes you wonder, doesn&#8217;t it? Lest you think I&#8217;m exaggerating, here&#8217;s some of the call stacks for our #2 function, <code>malloc</code>:</p>
<p><a href="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png"><img loading="lazy" data-attachment-id="1315" data-permalink="https://fgiesen.wordpress.com/2013/01/30/a-string-processing-rant/hotspots_malloc/" data-orig-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png" data-orig-size="497,205" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Loading hotspots: calls to malloc()" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png?w=497" src="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png?w=497&#038;h=205" alt="Loading hotspots: calls to malloc()" width="497" height="205" class="aligncenter size-full wp-image-1315" srcset="https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png 497w, https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png?w=150&amp;h=62 150w, https://fgiesen.files.wordpress.com/2013/01/hotspots_malloc.png?w=300&amp;h=124 300w" sizes="(max-width: 497px) 100vw, 497px" /></a></p>
<p>Here&#8217;s the callers to #5, <code>free</code>:</p>
<p><a href="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png"><img loading="lazy" data-attachment-id="1313" data-permalink="https://fgiesen.wordpress.com/2013/01/30/a-string-processing-rant/hotspots_free/" data-orig-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png" data-orig-size="497,245" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Loading hotspots: calls to free()" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png?w=497" src="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png?w=497&#038;h=245" alt="Loading hotspots: calls to free()" width="497" height="245" class="aligncenter size-full wp-image-1313" srcset="https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png 497w, https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png?w=150&amp;h=74 150w, https://fgiesen.files.wordpress.com/2013/01/hotspots_free.png?w=300&amp;h=148 300w" sizes="(max-width: 497px) 100vw, 497px" /></a></p>
<p>And here&#8217;s <code>memcpy</code>, further down:</p>
<p><a href="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png"><img loading="lazy" data-attachment-id="1316" data-permalink="https://fgiesen.wordpress.com/2013/01/30/a-string-processing-rant/hotspots_memcpy/" data-orig-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png" data-orig-size="493,132" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Loading hotspots: calls to memcpy()" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png?w=493" src="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png?w=493&#038;h=132" alt="Loading hotspots: calls to memcpy()" width="493" height="132" class="aligncenter size-full wp-image-1316" srcset="https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png 493w, https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png?w=150&amp;h=40 150w, https://fgiesen.files.wordpress.com/2013/01/hotspots_memcpy.png?w=300&amp;h=80 300w" sizes="(max-width: 493px) 100vw, 493px" /></a></p>
<p>I have to say, I&#8217;ve done optimization work on lots of projects over the years, and it&#8217;s rare that you&#8217;ll see a single piece of functionality leave a path of destruction <em>this</em> massive in its wake. The usual patterns you&#8217;ll see are either &#8220;localized performance hog&#8221; (a few functions completely dominating the profile, like I saw in the first round with the texture loading) or the &#8220;death by a thousand paper cuts&#8221;, where the profile is dominated by lots of &#8220;middle-man&#8221; functions that let someone else do the actual work but add a little overhead each time. As you can see, that&#8217;s not what&#8217;s going on here. What we have here is the rare &#8220;death in all directions&#8221; variant. Why settle for paper cuts, just go straight for the damn cluster bomb!</p>
<p>At this point it was clear that the whole config file thing needed some serious work. But first, I was curious. Config file loading and config block handling, sure. But what was that <code>RemoveWhitespace</code> function doing there? So I took a look.</p>
<h3>How not to remove whitespace</h3>
<p>Let&#8217;s cut straight to the chase: Here&#8217;s the code.</p>
<pre>
void RemoveWhitespace(cString &amp;szString)
{
    // Remove leading whitespace
    size_t nFirstIndex = szString.find_first_not_of(_L(' '));
    if(nFirstIndex != cString::npos)
    {
        szString = szString.substr(nFirstIndex);
    }

    // Remove trailing newlines
    size_t nLastIndex = szString.find_last_not_of(_L('\n'));
    while(nLastIndex != szString.length()-1)
    {
        szString.erase(nLastIndex+1,1);
        nLastIndex = szString.find_last_not_of(_L('\n'));
    };
    // Tabs
    nLastIndex = szString.find_last_not_of(_L('\t'));
    while(nLastIndex != szString.length()-1)
    {
        szString.erase(nLastIndex+1,1);
        nLastIndex = szString.find_last_not_of(_L('\t'));
    };
    // Spaces
    nLastIndex = szString.find_last_not_of(_L(' '));
    while(nLastIndex != szString.length()-1)
    {
        szString.erase(nLastIndex+1,1);
        nLastIndex = szString.find_last_not_of(_L(' '));
    };
}
</pre>
<p>As my current and former co-workers will confirm, I&#8217;m generally a fairly calm, relaxed person. However, in moments of extreme frustration, I will (on occasion) perform a &#8220;*headdesk*&#8221;, and do so properly.</p>
<p>This code did not drive me quite that far, but it was a close call.</p>
<p>Among the many things this function does wrong are:</p>
<ul>
<li>While it&#8217;s supposed to strip all leading and trailing white space (not obvious from the function itself, but clear in context), it will only trim leading spaces. So for example leading tabs won&#8217;t get stripped, nor will any spaces that follow after those tabs.</li>
<li>The function will remove trailing spaces, tabs, and newlines &#8211; provided they occur in exactly that order: first all spaces, then all tabs, then all newlines. But the string &#8220;test\t \n&#8221; will get trimmed to &#8220;test\t&#8221; with the tab still intact, because the tab-stripping loop will only tabs that occur at the end of the string after the newlines have been removed.</li>
<li>It removes white space characters it finds front to back rather than back to front. Because of the way C/C++ strings work, this is an O(N<sup>2</sup>) operation. For example, take a string consisting only of tabs.</li>
<li>The substring operation creates an extra temporary string; while not horrible by the standards of what else happens in this function, it&#8217;s now becoming clear why <code>RemoveWhitespace</code> manages to feature prominently in the call stacks for <code>malloc</code>, <code>free</code> and <code>memcpy</code> at the same time.</li>
<li>And let&#8217;s not even talk about how many times the string is scanned from front to back.</li>
</ul>
<p>That by itself would be bad enough. But it turns out that in context, not only is this function badly implemented, most of the work it does is completely unnecessary. Here&#8217;s one of its main callers, <code>ReadLine</code>:</p>
<pre>
CPUTResult ReadLine(cString &amp;szString, FILE *pFile)
{
    // TODO: 128 chars is a narrow line.  Why the limit?
    // Is this not really reading a line, but instead just reading the next 128 chars to parse?
    TCHAR   szCurrLine[128] = {0};
    TCHAR *ret = fgetws(szCurrLine, 128, pFile);
    if(ret != szCurrLine)
    {
        if(!feof(pFile))
        {
            return CPUT_ERROR_FILE_ERROR;
        }
    }

    szString = szCurrLine;
    RemoveWhitespace(szString);

    // TODO: why are we checking feof twice in this loop?
    // And, why are we using an error code to signify done?
    // eof check should be performed outside ReadLine()
    if(feof(pFile))
    {
        return CPUT_ERROR_FILE_ERROR;
    }

    return CPUT_SUCCESS;
}
</pre>
<p>I&#8217;ll let the awesome comments speak for themselves &#8211; and for the record, no, this thing really is supposed to read a line, and the ad-hoc parser that comes after this will get out of sync if it&#8217;s ever fed a line with more than 128 characters in it.</p>
<p>But the main thing of note here is that <code>szString</code> is assigned from a C-style (wide) string. So the sequence of operations here is that we&#8217;ll first allocate a <code>cString</code> (which is a typedef for a <code>std::wstring</code>, by the way), copy the line we read into it, then call <code>RemoveWhitespace</code> which might create another temporary string in the <code>substr</code> call, to follow it up with several full-string scans and possibly memory moves.</p>
<p>Except all of this is completely unnecessary. Even if we need the output to be a <code>cString</code>, we can just start out with a subset of the C string to begin with, rather than taking the whole thing. All <code>RemoveWhitespace</code> really needs to do is tell us where the non-whitespace part of the string begins and ends. You can either do this using C-style string handling or, if you want it to &#8220;feel more C++&#8221;, you can express it by iterator manipulation:</p>
<pre>
static bool iswhite(int ch)
{
    return ch == _L(' ') || ch == _L('\t') || ch == _L('\n');
}

template
static void RemoveWhitespace(Iter&amp; start, Iter&amp; end)
{
    while (start &lt; end &amp;&amp; iswhite(*start))
        ++start;

    while (end &gt; start &amp;&amp; iswhite(*(end - 1)))
        --end;
}
</pre>
<p>Note that this is not only much shorter, it also correctly deals with all types of white space both at the beginning and the end of the line. Instead of the original string assignment we then do:</p>
<pre>
    // TCHAR* obeys the iterator interface, so...
    TCHAR* start = szCurrLine;
    TCHAR* end = szCurrLine + tcslen(szCurrLine);
    RemoveWhitespace(start, end);
    szString.assign(start, end);
</pre>
<p>Note how I use the iterator range form of <code>assign</code> to set up the string with a single copy. No more substring operations, no more temporaries or O(N<sup>2</sup>) loops, and after reading we scan over the entire string no more than two times, one of those being in <code>tcslen</code>. (<code>tcslen</code> is a MS extension that is the equivalent of <code>strlen</code> for <code>TCHAR</code> &#8211; which might be either plain <code>char</code> or <code>wchar_t</code>, depending on whether <code>UNICODE</code> is defined &#8211; this code happens to be using &#8220;Unicode&#8221;, that is, UTF-16).</p>
<p>There&#8217;s only two other calls to <code>RemoveWhitespace</code>, and both of these are along the same vein as the call we just saw, so they&#8217;re just as easy to fix up.</p>
<h3>Problem solved?</h3>
<p>Not quite. Even with the <code>RemoveWhitespace</code> insanity under control, we&#8217;re still reading several megabytes worth of text files with short lines, and there&#8217;s still between 1 and 3 temporary string allocations per line in the code, plus whatever allocations are needed to actually store the data in its final location in the <code>CPUTConfigBlock</code>.</p>
<p>Long story short, this code still badly needed to be rewritten to do less string handling, so I did. My new code just reads the file into a memory buffer in one go (the app in question takes 1.5GB of memory in its original form, we can afford to allocate 650K for a text file in one block) and then implements a more reasonable scanner that processes the data in place and doesn&#8217;t do any string operations until we need to store values in their final location. Now, because the new scanner assumes that ASCII characters end up as ASCII, this will actually not work correctly with some character encodings such as Shift-JIS, where ASCII-looking characters can appear in the middle of encodings for multibyte characters (the config file format mirrors INI files, so &#8216;[&#8216;, &#8216;]&#8217; and &#8216;=&#8217; are special characters, and the square brackets can appear as second characters in a Shift-JIS sequence). It does however still work with US-ASCII text, the ISO Latin family and UTF-8, which I decided was acceptable for a config file reader. I did still want to support Unicode characters as identifiers though, which meant I was faced with a problem: once I&#8217;ve identified all the tokens and their extents in the file, surely it shouldn&#8217;t be hard to turn the corresponding byte sequences into the <code>std::wstring</code> objects the rest of the code wants using standard C++ facilities? Really, all I need is a function with this signature:</p>
<pre>
void AssignStr(cString&amp; str, const char* begin, const char* end);
</pre>
<h3>Converting strings, how hard can it be?</h3>
<p>Turns out: quite hard. I could try using <code>assign</code> on my <code>cString</code> again. That &#8220;works&#8221;, if the input happens to be ASCII only. But it just turns each byte value into the corresponding Unicode code point, which is blatantly wrong if our input text file actually has any non-ASCII characters in it.</p>
<p>Okay, so we could turn our character sequence into a <code>std::string</code>, and then convert that into a <code>std::wstring</code>, never mind the temporaries for now, we can figure that out later&#8230; wait, WHAT? There&#8217;s actually no official way to turn a <code>string</code> containing multi-byte characters into a <code>wstring</code>? How moronic is that?</p>
<p>Okay, whatever. Screw C++. Just stick with C. Now there actually <em>is</em> a standard function to convert multi-byte encodings to <code>wchar_t</code> strings, and it&#8217;s called, in the usual &#8220;omit needless vowels&#8221; C style, <code>mbstowcs</code>. Only that function <em>can&#8217;t be used</em> on an input string that&#8217;s delimited by two pointers! Because while it accepts a size for the <em>output</em> buffer, it assumes the <em>input</em> is a 0-terminated C string. Which may be a reasonable protocol for most C string-handling functions, but is definitely problematic for something that&#8217;s typically used for input parsing, where you generally aren&#8217;t guaranteed to have NUL characters in the right places.</p>
<p>But let&#8217;s assume for a second that we&#8217;re willing to modify the input data (<code>const</code> be damned) and temporarily overwrite whatever is at <code>end</code> with a NUL character so we can use <code>mbstowcs</code> &#8211; and let me just remark at this point that awesomely, the Microsoft-extended safe version of <code>mbstowcs</code>, <code>mbstowcs_s</code>, accepts <em>two</em> arguments for the size of the output buffer, but still doesn&#8217;t have a way to control how many input characters to read &#8211; if you decide to extend a standard API anyway, why can&#8217;t you fix it at the same time? Anyway, if we just patch around in the source string to make <code>mbstowcs</code> happy, does that help us?</p>
<p>Well, it depends on how loose you&#8217;re willing to play with the C++ standard. The goal of the whole operation was to reduce the number of temporary allocations. Well, <code>mbstowcs</code> wants a <code>wchar_t</code> output buffer, and writes it like it&#8217;s a C string, including terminating NUL. <code>std::wstring</code> also has memory allocated, and normal implementations will store a terminating 0 <code>wchar_t</code>, but as far as I can tell, this is not actually guaranteed. In any case, there&#8217;s a problem, because we need to reserve the right number of wchar&#8217;s in the output string, but it&#8217;s not guaranteed to be safe to do this:</p>
<pre>
void AssignStr(cString&amp; str, const char* begin, const char* end)
{
    // patch a terminating NUL into *end
    char* endPatch = (char*) end;
    char oldEnd = *end;
    *endPatch = 0;

    // mbstowcs with NULL arg counts how many wchar_t's would be
    // generated
    size_t numOut = mbstowcs(NULL, begin, 0);

    // make sure str has the right size
    str.resize(numOut, ' ');

    // convert characters including terminating NUL and hope it's
    // going to be OK?
    mbstowcs(&amp;str[0], begin, numOut + 1);

    // restore the original end
    *endPatch = oldEnd;
}
</pre>
<p>This might work, or it might not. As far as I know, it would be legal for a <code>std::wstring</code> implementation to only append a trailing NUL character lazily whenever <code>c_str()</code> is first called on a particular string. Either way, it&#8217;s fairly gross. I suppose I could <code>resize</code> to <code>numOut + 1</code> elements, and then later do another resize after the <code>mbstowcs</code> is done; that way should definitely be safe.</p>
<p>Either way is completely beside the point though. This is an actual, nontrivial operation on strings that is a totally reasonable thing to do, and that the C IO system will in fact do for me implicitly if I use <code>fgetws</code>. <em>Why are all the functions dealing with this so horribly broken for this use case that&#8217;s not at all fancy?</em> Did anyone ever look at this and decide that it was reasonable to expect people to write code like this? WHAT THE HELL?</p>
<h3>It gets better</h3>
<p>That&#8217;s not it quite yet, though. Because when I actually wrote the code (as opposed to summarizing it for this blog post), I didn&#8217;t think to patch in the NUL byte on the source string. So I went for the alternative API that works character by character: the C function <code>mbtowc</code>. Now, awesomely, because it works character by character, and is not guaranteed to see all characters in a multi-byte sequence in the same call, it has to keep state around of which partial multi-byte sequences it has seen to be able to decode characters. So it&#8217;s not thread-safe, and POSIX defines an extended version <code>mbrtowc</code> that makes you pass in a pointer to that state which does make it thread-safe. At this point though, I don&#8217;t care about thread-safety (this code is single-threaded anyway), and besides, in our case I actually know that the characters between <code>begin</code> and <code>end</code> are supposed to parse correctly. So I just don&#8217;t worry about it. Also, instead of actually counting the right number of <code>wchar_t</code>&#8216;s ahead of time in a second pass, I just assume that the string is generally likely to have less wide characters than the source multi-byte string has bytes. Even if that turns out wrong (which won&#8217;t happen for conventional encodings), the <code>std::wstring</code> we write to can dynamically resize, so there&#8217;s not much that can go wrong. So I ended up with this implementation:</p>
<pre>
void AssignStr(cString&amp; dest, const char* begin, const char* end)
{
    dest.clear();
    if (end &lt;= begin)
        return;

    size_t len = end - begin;
    size_t initial = len + 1; // assume most characters are 1-byte
    dest.reserve(initial);

    const char* p = start;
    while (p &lt; end)
    {
        wchar_t wc;
        int len = mbtowc(&amp;wc, p, end - p);
        if (len &lt; 1) // NUL byte or error
            break;

        p += len;
        dest.push_back(wc);
    }
}
</pre>
<p>Looks fairly reasonable, right?</p>
<p>Well, one profiling session later, I noticed that performance had improved, but it turned out that I was apparently wrong to assume that, like its <code>std::vector</code> counterpart, <code>std::wstring::push_back</code> would basically compile into the moral equivalent of <code>dest.data[dest.len++] = wc</code>. Instead, what I saw in VTune (with a kind of morbid fascination) was about two dozen instructions worth of inlined insanity surrounding a call to <code>std::wstring::insert</code>. <em>For every character</em>. <b>In a release build</b>.</p>
<p>It&#8217;s probably the VC++ STL doing something stupid. At this point, I don&#8217;t feel like investigating why this is happening. Whatever, I&#8217;m just gonna add some more to this layer cake of insanity. Just stop thinking and start coding. So I figure that hey, if adding stuff to strings is apparently an expensive operation, well, let&#8217;s amortize it, eh? So I go for this:</p>
<pre>
void AssignStr(cString&amp; dest, const char* begin, const char* end)
{
    dest.clear();
    if (end &lt;= begin)
        return;

    static const int NBUF = 64;
    wchar_t buf[NBUF];
    int nb = 0;

    size_t len = end - begin;
    size_t initial = len + 1; // assume most characters are 1-byte
    dest.reserve(initial);

    const char* p = start;
    while (p &lt; end)
    {
        int len = mbtowc(&amp;buf[nb++], p, end - p);
        if (len &lt; 1) // NUL byte or error
            break;

        p += len;
        if (p &gt;= end || nb &gt;= NBUF)
        {
            dest.append(buf, buf + nb);
            nb = 0;
        }
    }
}
</pre>
<p>And it&#8217;s <em>still</em> slow, and I <em>still</em> get a metric ton of bullshit inlined for that call. Turns out this happens because I call the general &#8220;input iterator&#8221; variant of <code>append</code> which, go figure, adds character by character. Silly me! What I really should&#8217;ve called is <code>dest.append(buf, nb)</code>. Of course! Once I figure that one out, I profile again, and sure enough, this time there&#8217;s no magic <code>std::string</code> functions cluttering up the profile anymore. Finally. Mission accomplished, right?</p>
<h3>Not so fast, bucko.</h3>
<p>Ohhh no. No, there&#8217;s one final &#8220;surprise&#8221; waiting for me. I put surprise in quotes because we already saw it in my first profile screenshot.</p>
<p><a href="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png"><img loading="lazy" data-attachment-id="1332" data-permalink="https://fgiesen.wordpress.com/2013/01/30/a-string-processing-rant/hotspots_locale/" data-orig-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png" data-orig-size="497,130" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="The final surprise" data-image-description="" data-image-caption="" data-medium-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png?w=300" data-large-file="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png?w=497" src="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png?w=497&#038;h=130" alt="The final surprise" width="497" height="130" class="aligncenter size-full wp-image-1332" srcset="https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png 497w, https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png?w=150&amp;h=39 150w, https://fgiesen.files.wordpress.com/2013/01/hotspots_locale.png?w=300&amp;h=78 300w" sizes="(max-width: 497px) 100vw, 497px" /></a></p>
<p>Yeah right. Those C functions we&#8217;ve been calling? In the VC++ C runtime library, all of them end up calling a constructor for a C++ object for some reason.</p>
<p>No, I&#8217;m not gonna comment on that one. I stopped caring a few paragraphs ago. Go ahead, put C++ code in your C runtime library. Whatever makes you happy.</p>
<p>So it turns out that VC++ has two versions of all the multibyte conversion functions: one that uses the current locale (which you can query using <code>_get_current_locale()</code>) and one that takes an explicit <code>locale_t</code> parameter. And if you don&#8217;t pass in a locale yourself, <code>mbtowc</code> and so forth will call <code>_get_current_locale()</code> themselves, and that ends up calling a C++ constructor for some reason. (I don&#8217;t care, I&#8217;m in my happy place right now. La la la).</p>
<p>And I finally decide to screw portability &#8211; hey, it&#8217;s a VC++-only project anyway &#8211; and call <code>_get_current_locale()</code> once, pass it to all my calls, and the magic constructor disappears, and with it the last sign of dubious things happening in the string handling.</p>
<p>Hooray.</p>
<h3>Conclusions</h3>
<p>So, what do we have here: we have a C++ string class that evidently makes it easy to write horrendously broken code without noticing it, and simultaneously doesn&#8217;t provide some core functionality that apps which use both <code>std::wstring</code> <em>and</em> interface with non-UTF16 character sets (which is almost nobody, I&#8217;m sure!) will need. We have C functions that go out of their way to make it hard to use them correctly. We have the Microsoft camp that decides that the right way to fix these functions is to fix buffer overflows, and we have the POSIX camp that decides that the right way to fix them is to fix the race condition inherent in their global state. Both of these claim that their modifications are more important than the other&#8217;s, and then there&#8217;s the faction that holds the original C standard library to be the only true way, ignoring the fact that this API is clearly <em>horribly broken</em> no matter how you slice it. Meanwhile, <code>std::wstring</code> gets another attention fix by making it unnecessarily hard to actually get data from C APIs into it without extra copying (and may I remind you that I&#8217;m only using C APIs here because there doesn&#8217;t seem to be an official C++ API!), while the VC++ standard library proves its attention deficit by somehow making a <code>push_back</code> to a properly pre-allocated string an expensive operation. And for the final act of our little performance, watch as a constructor gets called from C code, a veritable Deus Ex Machina that I honestly didn&#8217;t see coming.</p>
<p>As my friend Casey Muratori would put it: <b>Everyone is fired.</b></p>
<p>And now excuse me while I apply some bandages and clean the blood off my desk.</p>
]]></html><thumbnail_url><![CDATA[https://fgiesen.files.wordpress.com/2013/01/hotspots_loading.png?fit=440%2C330]]></thumbnail_url><thumbnail_width><![CDATA[]]></thumbnail_width><thumbnail_height><![CDATA[]]></thumbnail_height></oembed>