Skip to content

Optimize TextOutputFormatter Accept-Charset sort - #67967

Merged
javiercn merged 9 commits into
mainfrom
optimize-textoutputformatter-sort
Jul 24, 2026
Merged

javiercn merged 9 commits into
mainfrom
optimize-textoutputformatter-sort

Conversation

@javiercn

@javiercn javiercn commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #67965.

TextOutputFormatter.Sort orders weighted Accept-Charset values before matching them against the supported encodings. The original implementation built an ascending list with a BinarySearch + List.Insert loop and then reversed it. That is pessimal for the realistic case where a header lists its most-preferred charset first (already descending by quality): every insert hits the front of the list and shifts every existing element, making the common case O(n²).

This replaces it with two paths, keyed on how many charsets the header declares:

Fast path — SortSmall (≤ 32 charsets, the only case real clients hit)

  • Sorts a stack-allocated int index buffer (stackalloc int[32]). StringWithQualityHeaderValue is a reference type so it can't live in a stackalloc buffer, but its indices can — so there is no heap scratch; the only allocation is the result List we have to return.
  • Builds the result directly in descending quality order with an insertion sort, filtering out q=0 (HeaderQuality.NoMatch) entries as it goes. For a preferred-first header each value just appends with no shifting → O(n) common case, and no trailing Reverse.
  • Worst case is an O(n²) insertion sort, which is irrelevant at ≤ 32 entries.
  • Shifting past equal-quality entries (QualityComparer.Compare(prev, value) <= 0) lands a later header entry ahead of earlier equals, preserving the previous last-entry-wins selection deterministically — no unstable framework sort, no original-index tie-break comparer needed.

Fallback — SortLarge (> 32 charsets, never happens in practice)

  • No real client sends more than a handful of charsets in a single Accept-Charset header, so this branch exists only for correctness. It uses a plain List.Sort(QualityComparer) + Reverse and does not preserve tie ordering — with that many client-declared charsets nothing observable can depend on how equal-quality values are ordered.

The sortNeeded scan and its allocation-free early return (returns the original values untouched when no explicit non-zero quality requires sorting) are unchanged.

Behavior preserved

  • Descending quality order.
  • q=0 entries excluded once sorting occurs.
  • A concrete charset is preferred over an equal-quality wildcard (QualityComparer orders wildcards below concrete values).
  • Wildcards still match a supported encoding.
  • Equal-quality concrete charsets keep the previous observable selection (last header entry wins) on the fast path.

Tests

Added characterization rows to SelectResponseCharacterEncodingData in TextOutputFormatterTests covering: no-quality fast path, descending-quality weighting, q=0 exclusion, concrete-over-wildcard, wildcard match, equal-quality last-wins, and a large weighted collection.

dotnet test src/Mvc/Mvc.Core/test/Microsoft.AspNetCore.Mvc.Core.Test.csproj --filter "FullyQualifiedName~TextOutputFormatterTests" → 23 passed, 0 failed, no new warnings.

Replace the per-element BinarySearch + List.Insert insertion sort in TextOutputFormatter.Sort with a single filtered copy into a pre-sized list followed by List.Sort and Reverse. Preserves the no-sort fast path, q=0 exclusion, and descending/wildcard selection behavior. Adds characterization test cases covering weighted, q=0, wildcard, equal-quality, and large-collection scenarios.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Copilot AI review requested due to automatic review settings July 22, 2026 19:36
@javiercn
javiercn requested a review from a team as a code owner July 22, 2026 19:36

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 TextOutputFormatter.Sort for weighted Accept-Charset values by replacing the previous repeated BinarySearch + List.Insert insertion-sort approach with a single List.Sort + Reverse over a pre-sized list, and adds characterization test rows to validate selection behavior across common weighting and wildcard scenarios.

Changes:

  • Reworks TextOutputFormatter.Sort to copy eligible values into a pre-sized list, sort once with StringWithQualityHeaderValueComparer.QualityComparer, then reverse for descending order.
  • Keeps the existing “no q-values present” fast path (no allocation) unchanged.
  • Adds new test data rows in TextOutputFormatterTests to cover weighting order, q=0 handling during sorting, wildcard behavior, and larger weighted inputs.

Reviewed changes

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

File Description
src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs Replaces insertion-sort-based ordering with a pre-sized list + List.Sort + Reverse for weighted Accept-Charset values.
src/Mvc/Mvc.Core/test/Formatters/TextOutputFormatterTests.cs Adds characterization rows for weighted sorting, q=0 exclusion (when sorting), wildcard behavior, equal-quality behavior, and a larger weighted header list.

javiercn and others added 6 commits July 22, 2026 23:01
…inistic

List.Sort is not stable, so equal-quality non-wildcard Accept-Charset values could reorder across runtimes and change the selected encoding. Track the original header index and break ties on it (later entry first), preserving the previous insertion-sort observable behavior and removing the now-unnecessary Reverse.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Replace the tuple/index list plus projection with a single result list whose backing array is sorted in place through CollectionsMarshal.AsSpan. An insertion sort (the lists are tiny) gives a deterministic descending order and preserves the previous last-entry-wins behavior for equal-quality values without a second allocation.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Insertion sort is O(n^2). Sort a small (stack-allocated) index buffer with the framework's introspective sort (O(n log n) worst case) using a struct IComparer, then materialize the result list in that order. Breaking equal-quality ties by original header position keeps the selection deterministic and preserves the previous last-entry-wins behavior without relying on sort stability.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Replace the interim selection sort with an insertion sort that builds the
result directly in descending quality order. Accept-Charset headers usually
list the preferred charset first, so already-descending input appends with
zero shifts (common case O(n)) and no trailing Reverse is needed. Shifting
past equal-quality entries preserves the previous last-entry-wins behavior.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Sort a scratch buffer of indices (stackalloc for <=32 entries, heap array
beyond) instead of the values or a second list. The framework span sort is an
introspective sort, so the worst case is O(n log n) with no insertion-sort
pathology, and a struct comparer that breaks quality ties on the original
index keeps the result deterministic and preserves the previous
last-entry-wins selection despite the sort being unstable.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
For realistic headers (<=32 charsets) sort a stack-allocated index buffer
with an insertion sort that builds descending order directly, preserving the
last-entry-wins tie behavior with zero heap scratch. No real client sends
more charsets than that, so the >32 branch just uses List.Sort + Reverse and
does not preserve tie ordering, since nothing observable can depend on it.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
@gfoidl gfoidl added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates label Jul 23, 2026
javiercn and others added 2 commits July 24, 2026 01:33
Adds a BenchmarkDotNet microbenchmark comparing the previous
(BinarySearch + Insert, ascending build then Reverse) and current
(stackalloc index buffer insertion build, List.Sort fallback >32) sort
implementations across header counts and input orderings, per PR review
request to quantify the change.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
Replace the stackalloc int[32] scratch in the SortSmall fast path with an
[InlineArray] struct buffer. The compiler puts stronger guarantees on inline
arrays (no stack cookie, better bounds analysis) for a tad faster code. Mirror
the change in the microbenchmark's inlined copy.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9a1e1b92-2930-4202-aa2e-683c18e65c9d
@javiercn
javiercn merged commit e909743 into main Jul 24, 2026
24 checks passed
@javiercn
javiercn deleted the optimize-textoutputformatter-sort branch July 24, 2026 08:42
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Jul 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve Accept-Charset sorting in TextOutputFormatter

4 participants