Repository navigation
Faster ordinal string comparison: find the first differing char with a bit scan - #136692
armanossiloko wants to merge 3 commits into
Conversation
|
Azure Pipelines: Successfully started running 3 pipeline(s). 13 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @dotnet/area-system-runtime |
…th a bit scan SpanHelpers.SequenceCompareTo(ref char, ...), which backs string.CompareOrdinal, string.Compare(..., StringComparison.Ordinal), StringComparer.Ordinal and span SequenceCompareTo for chars, compares 4 chars at a time (2 on 32-bit), but when a chunk differs it falls back to comparing char by char from the start of that chunk, with a data-dependent branch per char. On little-endian platforms, the lowest set bit of the XOR of the two chunks belongs to the first differing char, so find it with TrailingZeroCount and return directly. The 2-char step that follows the loop on 64-bit gets the same treatment. Both branch to a shared block after the method's normal exit, which keeps the JIT's layout of the short-string path unchanged. Big-endian platforms scan the chunk char by char as before. Return values are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
c9b30a9 to
79e36b0
Compare
| { | ||
| break; | ||
| differentBits = firstChars ^ secondChars; | ||
| goto Difference; |
There was a problem hiding this comment.
We do not want to be adding more goto, it can mess with control flow and make code harder to reason/understand about.
There was a problem hiding this comment.
Thanks, removed. The difference is now handled right after the loop: the loop only stops with a whole chunk left when that chunk differs, so a single check there calls a small inlined helper. The loop, the 2-char step and the trailing char loop are unchanged from main.
Before settling on this, I tried returning from inside the loop and tracking a "difference found" value through to the end. In both, the Tier 1 code (with SequenceCompareTo inlined into CompareOrdinalHelper) lost main's branchless 2-char step or took an extra jump per equal chunk, and short strings measured up to ~15% slower. The updated description has the numbers.
|
|
||
| Difference: | ||
| // The chars at i onwards differ within the bits in differentBits; find the first differing char. | ||
| if (BitConverter.IsLittleEndian) |
There was a problem hiding this comment.
You can just do a byte swap for big endian
There was a problem hiding this comment.
Done: the helper byte swaps on big-endian before the TrailingZeroCount, so the char-by-char fallback is gone.
| if (firstChars != secondChars) | ||
| { | ||
| break; | ||
| differentBits = firstChars ^ secondChars; |
There was a problem hiding this comment.
if this is going to be done, its better to do it as differenceBits = firstChars ^ secondChars then if (differenceBits != 0).
A comparison is functionally a subtract (1 cycle) that doesn't write a result, it just gives you the flags. An xor is the same 1 cycle and gives you the flags.
There was a problem hiding this comment.
Makes sense. The helper now computes differentBits = firstChars ^ secondChars once and asserts it's non-zero.
I kept the != in the loop itself as on main. When the loop computed the XOR and tested it, the JIT laid out the found-a-difference path as the fall-through, which added a taken jump for every equal chunk. That made short equal strings ~10% slower on my machine. Now the XOR only happens once, after the loop, on the chunk that differs.
… using goto Address review feedback on the ordinal char compare change: - Keep the 4-char (2-char on 32-bit) loop, the 2-char step and the trailing char loop exactly as on main, and handle a differing chunk after the loop: the loop only stops with a whole chunk left if that chunk differs. - Find the first differing char in a small inlined helper that XORs the two chunks and uses TrailingZeroCount, byte swapping first on big-endian, instead of a goto to a shared block. - The 2-char step no longer has its own bit scan, so its branchless form from main is kept. Return values are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous run failed only in tests tracked as known issues (#134815 / #130439 WebSockets on Android, #136685 WASI System.Net.Http.Functional.Tests timeout). No code changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Just cleaning up old issues and PRs. |
Summary
SpanHelpers.SequenceCompareTo(ref char, int, ref char, int)is the core of:string.CompareOrdinalstring.Compare(..., StringComparison.Ordinal)andstring.CompareTowith ordinal semanticsStringComparer.OrdinalMemoryExtensions.SequenceCompareToforcharspansIt compares 4 chars at a time (2 on 32-bit). When a chunk differs, it falls back to comparing char by char from the start of that chunk, with one data-dependent branch per char.
The loop only stops with a whole chunk left when that chunk differs. This PR handles that case right after the loop: a small inlined helper XORs the two chunks and finds the first differing char with
BitOperations.TrailingZeroCount. On big-endian, it byte swaps first, so that the lowest set bit still belongs to the first char.The loop, the 2-char step on 64-bit and the trailing char loop are unchanged from
main. Return values are unchanged: still the difference of the first differing chars, or the length difference.Performance
Windows 10 x64, Intel Core i9-9900K (AVX2). Release builds of
mainat 294b271 and of this PR. Each benchmark first runs all cases once unreported so that tiering has settled. Values are medians of 8 interleaved runs that rotate the order of the builds.Placebo. The tables include a third build, a placebo. It is
mainplus one no-op condition at the top of the method (|| (firstLength | secondLength) == 0added to theUnsafe.AreSamecheck). That condition changes no results and only shifts the code that follows by a few bytes. On this CPU the placebo alone measures between 0.82× and 1.15× on the short cases below. Differences of that size at short lengths come from code placement, most likely the JCC erratum mitigation on Skylake-derived cores, rather than from the change itself. For comparison,mainagainst a byte-identical copy of itself stays within ±1–5% at the median.Array.Sort(string[], StringComparer.Ordinal), best of 9 per run:"key_" + number(12 chars)string.CompareOrdinalon 4,096 pairs of distinct string instances of length L (columns), as speedups overmain:mainmainThe gains come where a difference falls inside a chunk, which is the common case when sorting or searching. The slowest cells for this PR are 0.92–0.95×, at 4–12 chars on equal strings or strings that differ in the last char. Those paths execute the same instructions as on
main, and they are within the range of the placebo.Validation
System.Runtime.Tests: 78,658 tests on x64, 77,863 on x86System.Memory.Tests: 52,935System.Collections.Tests: 33,958System.Net.Requests.Tests: 1,215System.Memory.Testson x86, the process crashed incoreclr!PgoManager::getPgoInstrumentationResultsduring background tier-1 JIT. That is Crash: access violation in coreclr!PgoManager::getPgoInstrumentationResults during tier-1 background JIT (Windows x86) #134695; the other 13 runs passed.ReadOnlySpan<char>.SequenceCompareTo,string.CompareOrdinalandstring.Compare(..., StringComparison.Ordinal)against a scalar reference on 3,000,000 random pairs.mainand on this PR, on both x64 and x86.🤖 Generated with Claude Code