Performance Tuning for .NET Core
&gt; Reduce branching &amp; branch misprediction<p>I wrote a parser for a &quot;formalized&quot; URI (it looked somewhat like OData). This parser was being invoked millions of times and was adding minutes to an operation - it dominated the profile at something like 30% CPU time. It started off something like this:<p><pre><code>    int state = State_Start;
    for (var i = 0; i &lt; str.Length; i++)
    {
        var c = str[i];
        switch (state)
        {
            case State_Start:
                &#x2F;* Handle c for this state. *&#x2F;
                &#x2F;* Update state if a new state is reached. *&#x2F;
        }
    }
</code></pre>
Hardly rocket science, a clear-as-day miniature state machine. VTune was screaming about the switch, so I changed it to this:<p><pre><code>    for (var i = 0; i &lt; str.Length; i++)
    {
        for (; i &lt; str.Length; i++)
        {
            var c = str[i];
            &#x2F;* Handle c for this state. *&#x2F;
            &#x2F;* Break if a new state is reached. *&#x2F;
        }
        
        for (; i &lt; str.Length; i++)
        {
            var c = str[i];
            &#x2F;* Handle c for this state. *&#x2F;
            &#x2F;* Break if a new state is reached. *&#x2F;
        }
    }
</code></pre>
The new profile put the function at &lt; 0.1% of CPU time. This is something that the &quot;premature optimization crowd&quot; (who tend to partially quote Knuth concerning optimization) get wrong: death by a thousand cuts. A <i>single</i> branch in the source (it ends up being more in machine code) was costing 30% performance.