Skip to content

Faster ordinal string comparison: find the first differing char with a bit scan - #136692

Closed
armanossiloko wants to merge 3 commits into
dotnet:mainfrom
armanossiloko:perf/ordinal-compare-tzcnt
Closed

armanossiloko wants to merge 3 commits into
dotnet:mainfrom
armanossiloko:perf/ordinal-compare-tzcnt

Conversation

@armanossiloko

@armanossiloko armanossiloko commented Oct 30, 2026 •

Copy link
Copy Markdown

Summary

SpanHelpers.SequenceCompareTo(ref char, int, ref char, int) is the core of:

  • string.CompareOrdinal
  • string.Compare(..., StringComparison.Ordinal) and string.CompareTo with ordinal semantics
  • StringComparer.Ordinal
  • MemoryExtensions.SequenceCompareTo for char spans

It 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 above only stops with a whole chunk left if the chunk differs.
if (minLength >= (i + (nuint)(sizeof(nuint) / sizeof(char))))
{
    return CompareFirstDifferentChar(ref Unsafe.Add(ref first, (nint)i), ref Unsafe.Add(ref second, (nint)i));
}

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 main at 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 main plus one no-op condition at the top of the method (|| (firstLength | secondLength) == 0 added to the Unsafe.AreSame check). 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, main against a byte-identical copy of itself stays within ±1–5% at the median.

Array.Sort(string[], StringComparer.Ordinal), best of 9 per run:

sort 200,000 strings main PR speedup placebo
"key_" + number (12 chars) 63.7 ms 56.6 ms 1.13× 0.98×
GUIDs (36 chars) 54.2 ms 51.1 ms 1.06× 0.98×
file paths (~40 chars, long common prefix) 84.7 ms 81.4 ms 1.04× 0.97×
random lowercase words (3–10 chars) 57.6 ms 56.7 ms 1.02× 1.01×
2-char strings 27.4 ms 27.4 ms 1.00× 0.99×

string.CompareOrdinal on 4,096 pairs of distinct string instances of length L (columns), as speedups over main:

this PR vs. main 1 2 3 4 5 6 7 8 9 12 16 17 24 32 33 64 256
differ at a random position (or equal) 1.01× 0.97× 0.95× 0.95× 0.96× 1.15× 1.16× 1.11× 1.12× 1.22× 1.23× 1.23× 1.35× 1.35× 1.34× 1.26× 1.18×
differ in the last char 1.00× 0.97× 0.96× 0.94× 0.93× 1.15× 0.96× 0.93× 0.92× 0.94× 0.98× 0.96× 1.02× 1.03× 0.99× 1.01× 0.99×
equal (different instances) 0.96× 0.98× 0.99× 0.94× 0.94× 0.95× 0.96× 0.96× 0.96× 0.95× 1.00× 1.00× 1.05× 1.03× 1.03× 1.00× 0.98×
differ in the first char 1.01× 1.01× 1.02× 1.00× 1.07× 1.04× 1.01× 1.02× 1.02× 1.02× 1.00× 0.99× 0.99× 0.99× 1.00× 0.98× 0.96×
placebo vs. main 1 2 3 4 5 6 7 8 9 12 16 17 24 32 33 64 256
differ at a random position (or equal) 1.00× 0.96× 0.93× 0.93× 0.89× 0.89× 0.91× 0.91× 0.83× 0.85× 0.85× 0.82× 0.89× 0.92× 0.93× 0.95× 0.96×
differ in the last char 1.10× 0.96× 0.89× 0.88× 0.89× 0.91× 0.93× 0.91× 0.93× 0.92× 0.96× 0.97× 0.95× 0.97× 0.97× 0.99× 1.00×
equal (different instances) 0.97× 0.99× 0.94× 0.86× 0.87× 0.92× 0.93× 0.93× 0.93× 0.93× 0.97× 0.97× 0.95× 0.99× 0.98× 0.99× 0.98×
differ in the first char 1.10× 1.09× 1.09× 1.07× 1.15× 1.08× 1.05× 1.06× 1.05× 1.04× 1.01× 1.01× 1.00× 1.00× 1.00× 0.97× 0.96×

The 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

  • These suites pass locally against this build on both x64 and x86. No tests were changed.
    • System.Runtime.Tests: 78,658 tests on x64, 77,863 on x86
    • System.Memory.Tests: 52,935
    • System.Collections.Tests: 33,958
    • System.Net.Requests.Tests: 1,215
  • In 1 of 14 runs of System.Memory.Tests on x86, the process crashed in coreclr!PgoManager::getPgoInstrumentationResults during 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.
  • A differential check compared ReadOnlySpan<char>.SequenceCompareTo, string.CompareOrdinal and string.Compare(..., StringComparison.Ordinal) against a scalar reference on 3,000,000 random pairs.
    • Lengths ranged over 0–80 and start offsets over 0–3 (unaligned).
    • The alphabets had 3, 128 or 65,536 values, so the high-bit and surrogate ranges are covered.
    • A hash of all 9,000,000 return values is identical on main and on this PR, on both x64 and x86.
  • I haven't been able to run Arm64 or a big-endian platform.

🤖 Generated with Claude Code

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 30, 2026
@azure-pipelines

Copy link
Copy Markdown
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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.

…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]>
{
break;
differentBits = firstChars ^ secondChars;
goto Difference;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not want to be adding more goto, it can mess with control flow and make code harder to reason/understand about.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can just do a byte swap for big endian

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@armanossiloko

Copy link
Copy Markdown
Author

Just cleaning up old issues and PRs.

@jkotas jkotas added the tenet-performance Performance related issue label Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Runtime community-contribution Indicates that the PR has been added by a community member tenet-performance Performance related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants