Skip to content

[iOS] Optimize CompareStringNative performance - #130691

Merged
matouskozak merged 1 commit into
mainfrom
matouskozak-ios-string-sorting-perf
Jul 20, 2026
Merged

matouskozak merged 1 commit into
mainfrom
matouskozak-ios-string-sorting-perf

Conversation

@matouskozak

@matouskozak matouskozak commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Help with #121204

Problem

String sorting on iOS is significantly slower than other platforms. Profiling CompareStringNative shows stringByFoldingWithOptions consumes ~9% of native time — but it's redundant because compare:options:range:locale: with NSLiteralSearch already handles NSCaseInsensitiveSearch, NSDiacriticInsensitiveSearch, and NSWidthInsensitiveSearch on precomposed strings.

Root Cause

The folding step was added in PR #96002 (IgnoreKanaType support, Dec 2023) as a structural refactoring to make CompareStringNative parallel the pattern in GetSortKeyNative. The original working implementation (PR #86895, May 2023) had no folding and passed CI.

Change

Remove the redundant stringByFoldingWithOptions call from CompareStringNative. The compare:options:range:locale: API already applies all the comparison options directly.

Verified with 20 edge-case tests covering: IgnoreCase, IgnoreNonSpace (diacritics: é/e, ñ/n, À/A, combining marks), IgnoreWidth (fullwidth/halfwidth katakana), dakuten (ガ/カ), and all option combinations — zero mismatches between the fold+compare and direct compare approaches.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR optimizes Apple hybrid globalization collation on iOS / MacCatalyst by reducing per-call work in CompareStringNative and GetSortKeyNative, targeting hot-path string comparisons during sorting.

Changes:

  • Adds a small native cache for NSLocale keyed by the locale name (with an os_unfair_lock).
  • Avoids copying managed UTF-16 buffers by creating NSString instances via CFStringCreateWithCharactersNoCopy.
  • Narrows when stringByFoldingWithOptions is performed (intended to avoid redundant folding for some options).

Copilot AI review requested due to automatic review settings July 14, 2026 14:45
@matouskozak
matouskozak force-pushed the matouskozak-ios-string-sorting-perf branch from b1ce830 to ef31e85 Compare July 14, 2026 14:45
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:45 — with GitHub Actions Inactive
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:45 — with GitHub Actions Inactive
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:48 — with GitHub Actions Inactive
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:48 — with GitHub Actions Inactive
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:48 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated 2 comments.

@matouskozak matouskozak added the os-ios Apple iOS label Jul 14, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'os-ios': @vitek-karas, @kotlarmilos, @steveisok, @akoeplinger
See info in area-owners.md if you want to be subscribed.

Copilot AI review requested due to automatic review settings July 14, 2026 14:54
@matouskozak
matouskozak force-pushed the matouskozak-ios-string-sorting-perf branch from ef31e85 to cad4e8c Compare July 14, 2026 14:54
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:54 — with GitHub Actions Inactive
@matouskozak
matouskozak temporarily deployed to copilot-pat-pool July 14, 2026 14:55 — with GitHub Actions Inactive
@matouskozak

Copy link
Copy Markdown
Member Author

/azp run runtime-ioslike,runtime-maccatalyst,runtime-ioslikesimulator

@matouskozak
matouskozak marked this pull request as ready for review July 15, 2026 18:26
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

src/native/libs/System.Globalization.Native/pal_collation.m:108

  • The PR description lists additional optimizations (locale caching, zero-copy string creation, empty/NULL handling), but CompareStringNative still recreates NSLocale via GetCurrentLocale and still builds NSString instances by copying UTF-16 buffers. If those changes were dropped, the PR metadata should be updated to match; otherwise the implementation is incomplete relative to the stated scope.
        NSStringCompareOptions options = ConvertFromCompareOptionsToNSStringCompareOptions((CompareOptions)comparisonOptions, true);
        NSRange comparisonRange = NSMakeRange(0, sourceStrPrecomposed.length);
        return (int32_t)[sourceStrPrecomposed compare:targetStrPrecomposed
                                     options:options
                                     range:comparisonRange

@matouskozak

Copy link
Copy Markdown
Member Author

/azp run runtime-extra-platforms

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@matouskozak

Copy link
Copy Markdown
Member Author

/azp run runtime-extra-platforms

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@tarekgh tarekgh left a comment

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.

LGTM!

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow state for the Holistic Review Orchestrator.

{
  "version": 5,
  "last_dispatched_commit": "9f25b0ec2488144abd4340b652aaf48f5e75d9f2",
  "last_dispatched_base_ref": "main",
  "last_dispatched_base_sha": "2b4d69bfe02dc60350f7dc18cb5d04045a22cf69",
  "last_reviewed_commit": "9f25b0ec2488144abd4340b652aaf48f5e75d9f2",
  "last_reviewed_base_ref": "main",
  "last_reviewed_base_sha": "2b4d69bfe02dc60350f7dc18cb5d04045a22cf69",
  "last_recorded_worker_run_id": "29690755761",
  "review_attempt_commit": "",
  "review_attempt_base_ref": "",
  "review_attempt_count": 0,
  "max_review_attempts": 5,
  "review_history_format": "holistic-review-disclosure-v1",
  "review_history": [
    {
      "commit": "9f25b0ec2488144abd4340b652aaf48f5e75d9f2",
      "review_id": 4730929402
    }
  ]
}

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Holistic Review

Motivation: String sorting on iOS/HybridGlobalization is measurably slower than other platforms, and profiling attributes ~9% of native time in CompareStringNative to stringByFoldingWithOptions. The PR claims this fold step is redundant because -[NSString compare:options:range:locale:] already applies the case/diacritic/width insensitivity flags directly. The motivation is credible and backed by a linked issue (#121204).

Approach: The change removes the pre-fold block (fold source and target with ConvertFromCompareOptionsToNSStringCompareOptions(..., false)) from GlobalizationNative_CompareStringNative, leaving the subsequent compare:options:range:locale: call — which already builds the full option mask via the isLiteralSearchSupported = true overload — to perform the comparison. This is a targeted 7-line deletion with no behavioral flag changes.

Summary: The approach is sound and well-supported by the surrounding code. The sibling search paths in this same file — IndexOf/LastIndexOf, StartsWith, and EndsWith — never applied a folding pass and have relied solely on compare/NSStringCompareOptions since the original PR #86895. CompareStringNative was the outlier, having acquired the fold step in PR #96002 as a structural refactor. Removing it restores consistency with those working, shipping paths rather than introducing a novel comparison strategy, which substantially lowers correctness risk.

One genuine semantic difference between fold+compare and direct-compare is NSLiteralSearch: the removed fold call passed isLiteralSearchSupported = false (no NSLiteralSearch), while the retained compare uses true (adds NSLiteralSearch). Because both source and target are already normalized via precomposedStringWithCanonicalMapping before comparison, literal (code-point) matching on canonically-precomposed strings is equivalent for the supported option set, so this difference is benign. The IgnoreKanaType katakana transform is preserved and still runs before the comparison, so kana behavior is unaffected.

Risk is low and confined to iOS-like/MacCatalyst HybridGlobalization. The author reports validating 20 edge cases (IgnoreCase, IgnoreNonSpace with combining marks, IgnoreWidth fullwidth/halfwidth katakana, dakuten, and combinations) with zero mismatches, and the relevant runtime-ioslike, runtime-maccatalyst, and runtime-extra-platforms pipelines were triggered. I'd only reiterate the standard caution: existing CompareInfo/sorting tests across the full CompareOptions matrix on these platforms are the real gate — as long as those pass in CI, this is a safe optimization. No actionable code findings.

Verdict: LGTM.

Note

This review was generated by this repository's Holistic Review agentic workflow to complement the built-in Copilot review.

Generated by Holistic Review · 67.3 AIC · ⌖ 10.5 AIC · ⊞ 10K

@matouskozak

Copy link
Copy Markdown
Member Author

/ba-g failures are not related to changes in this PR

@matouskozak
matouskozak merged commit 630a700 into main Jul 20, 2026
211 of 235 checks passed
@matouskozak
matouskozak deleted the matouskozak-ios-string-sorting-perf branch July 20, 2026 08:13
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 23, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 9f25b0ec Deployed Jul 15, 2026 by matouskozak via conclusion #15226
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants