Repository navigation
Optimize TextOutputFormatter Accept-Charset sort - #67967
Merged
Merged
Conversation
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
Contributor
There was a problem hiding this comment.
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.Sortto copy eligible values into a pre-sized list, sort once withStringWithQualityHeaderValueComparer.QualityComparer, then reverse for descending order. - Keeps the existing “no q-values present” fast path (no allocation) unchanged.
- Adds new test data rows in
TextOutputFormatterTeststo 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. |
…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
reviewed
Jul 23, 2026
DeagleGross
reviewed
Jul 23, 2026
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
DeagleGross
approved these changes
Jul 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #67965.
TextOutputFormatter.Sortorders weightedAccept-Charsetvalues before matching them against the supported encodings. The original implementation built an ascending list with aBinarySearch+List.Insertloop 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)intindex buffer (stackalloc int[32]).StringWithQualityHeaderValueis a reference type so it can't live in astackallocbuffer, but its indices can — so there is no heap scratch; the only allocation is the resultListwe have to return.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 trailingReverse.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)Accept-Charsetheader, so this branch exists only for correctness. It uses a plainList.Sort(QualityComparer)+Reverseand does not preserve tie ordering — with that many client-declared charsets nothing observable can depend on how equal-quality values are ordered.The
sortNeededscan and its allocation-free early return (returns the originalvaluesuntouched when no explicit non-zero quality requires sorting) are unchanged.Behavior preserved
q=0entries excluded once sorting occurs.QualityComparerorders wildcards below concrete values).Tests
Added characterization rows to
SelectResponseCharacterEncodingDatainTextOutputFormatterTestscovering: no-quality fast path, descending-quality weighting,q=0exclusion, 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.