Answers inline...<br clear="all"><br><div class="gmail_quote">On Thu, Jul 15, 2010 at 4:20 PM, Nate Lawson <span dir="ltr">&lt;<a href="mailto:nate@rootlabs.com">nate@rootlabs.com</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">Andrew Arnott wrote:<br>
&gt; These six lines of code turn out to be ~*100 times slower* than the built-in<br>
&gt; .NET String.Equals function.  I don&#39;t know why there is such a perf<br>
&gt; difference, but apparently .NET has some serious string equality check<br>
&gt; optimizations in their native code.  Has anyone else compared the<br>
&gt; performance of their language&#39;s native string equality check function and<br>
&gt; this hand-written alternative?<br>
<br>
</div>We&#39;re doing that as part of our talk. Did you compare 100% correct<br>
strings or were they different? Obviously, a compare that terminates<br>
early will be faster for non-matching input.<br></blockquote><div><br></div><div>I test two strings.  One is a total mismatch (which means only one character is compared in the insecure case), and the other is a match except for the very last character (so all characters are compared, but it still fails).  </div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<br>
When you say 100x slower, what are your actual numbers in terms of<br>
nanoseconds per byte for each version?<br></blockquote><div><br></div><div>Upon measuring again, I see it is 30X slower rather than 100X I don&#39;t know if it was a timing difference or a miscalculation the first time.  In .NET String.Equals, each character takes .39 nanoseconds, in the bitwise XOR operation each character takes 11.88 nanoseconds.  Just to double-check my math conversion routine, here are the numbers again in scientific notation: </div>
<div>String.Equals: 3.912E-10 seconds per character</div><div>XOR method: 1.189E-08 seconds per character</div><div><br></div><div>My method of measure was to compare 5000 character strings 4000 times, then to divide the elapsed time for each method by 5000*4000.</div>
<div><br></div><div>I tried &quot;more obvious&quot; implementations that just did == and set boolean flags, but they were even slower than XOR, and had a greater time variation depending on how closely the string matched than the XOR method did.  So I guess the XOR method is the way to go (at least for .NET).</div>
</div>