Skip to content

Reduce allocations in output formatter content negotiation - #70166

Closed
davidfowl wants to merge 5 commits into
mainfrom
perf/content-negotiation-allocs
Closed

davidfowl wants to merge 5 commits into
mainfrom
perf/content-negotiation-allocs

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Reduce allocations in output formatter content negotiation

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. (Small perf change found in a perf survey, no issue.)

Remove small allocations from output formatter content negotiation

Description

Every ObjectResult/OkObjectResult response goes through DefaultOutputFormatterSelector. This PR removes a few small allocations from that path.

  • DefaultOutputFormatterSelector.GetAcceptableMediaTypes: return Array.Empty when there is no Accept header, so we no longer allocate a List<MediaTypeSegmentWithQuality> for it. When there is a header, the list is pre-sized from the number of comma-separated entries, so a single application/json no longer allocates a 4-element backing array.
  • AcceptHeaderParser: add an internal StringValues overload so the header isn't boxed to IList<string>. The per-value parsing loop is shared with the existing overload and is unchanged.
  • TextOutputFormatter.GetAcceptCharsetHeaderValues: return Array.Empty when there is no Accept-Charset header, which avoids boxing the StringValues.
  • SelectFormatterNotUsingContentType / SelectFormatterUsingAnyAcceptableContentType: use indexed loops over IList<IOutputFormatter> and MediaTypeCollection instead of foreach, which boxed the enumerator.

No public API or behavior changes. Formatter selection order, sorting and the selected content type are the same.

Results

I added ObjectResultExecutorBenchmark, which runs ObjectResultExecutor.ExecuteAsync with the HttpNoContent, String, Stream and SystemTextJson formatters. These are local BenchmarkDotNet runs (--config profile, 15 iterations) on a noisy 2-vCPU VM, with 3 interleaved A/B rounds. Each cell shows mean ± error.

Accept Round Before After Allocated before → after
(none) 1 787.9 ± 5.9 ns 905.6 ± 19.3 ns 712 B → 640 B (−10.1%)
(none) 2 875.4 ± 8.5 ns 883.5 ± 28.5 ns 712 B → 640 B
(none) 3 893.7 ± 24.0 ns 870.2 ± 13.3 ns 712 B → 640 B
application/json 1 1,196.5 ± 16.5 ns 1,260.4 ± 14.1 ns 792 B → 720 B (−9.1%)
application/json 2 1,229.0 ± 13.4 ns 1,243.9 ± 13.2 ns 792 B → 720 B
application/json 3 1,265.6 ± 10.1 ns 1,237.2 ± 45.5 ns 792 B → 720 B
browser text/html,...,*/*;q=0.8 1 1,683.4 ± 19.7 ns 1,747.6 ± 18.5 ns 832 B → 792 B (−4.8%)
browser text/html,...,*/*;q=0.8 2 1,693.0 ± 8.5 ns 1,681.0 ± 15.6 ns 832 B → 792 B
browser text/html,...,*/*;q=0.8 3 1,776.0 ± 49.0 ns 1,699.1 ± 17.0 ns 832 B → 792 B

The numbers are re-measured after the review feedback (bounded initial capacity; the benchmark now uses a fresh response body feature per invocation, which adds a constant ~216 B to both sides). Round 2 ran in reverse order (new first). Time is neutral within noise: round 1's base sample for the no-Accept case was an outlier that didn't reproduce.

Allocations drop by 40–72 B per response in every case. Time is neutral. Most of the remaining allocation comes from the benchmark harness (StreamResponseBodyFeature/StreamPipeWriter) and from Utf8JsonWriter, not from negotiation.

Tests

  • Added AcceptHeaderParserTest cases for the StringValues overload: multiple values, including empty and null entries, and StringValues.Empty.
  • Added DefaultOutputFormatterSelectorTest cases for multiple Accept header values sorted by quality across values, and for an empty Accept header value.
  • Microsoft.AspNetCore.Mvc.Core.Test: 4514 passed, 0 failed, 3 skipped.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

- Skip parsing and the List allocation in DefaultOutputFormatterSelector when there is no Accept header.
- Avoid boxing the Accept/Accept-Charset StringValues to IList<string>.
- Pre-size the parsed accept list from the number of comma separated entries.
- Use indexed loops over IList<IOutputFormatter> to avoid boxed enumerators.
- Add ObjectResultExecutorBenchmark.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 06:45
@github-actions github-actions Bot added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates label Oct 31, 2026

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.

🟡 Changes recommended

Unbounded capacity estimation can inflate allocations for tolerated headers, and alternating response-body feature reuse makes the benchmark’s per-response allocation measurements inconsistent.

2 open issues
What changed in this PR

Reduces allocations in MVC output formatter content negotiation while aiming to preserve formatter selection behavior.

Changes:

  • Avoids allocations for missing headers and boxing when parsing StringValues.
  • Pre-sizes Accept-header storage and replaces enumerator-based loops with indexed loops.
  • Adds parser and selector tests plus an end-to-end object-result execution benchmark.
File Description
src/​Mvc/​perf/​Microbenchmarks/​Microsoft.AspNetCore.Mvc/​ObjectResultExecutorBenchmark.cs Adds benchmarks for three Accept-header scenarios.
src/​Mvc/​Mvc.Core/​test/​Infrastructure/​DefaultOutputFormatterSelectorTest.cs Tests multi-value quality ordering and empty-header fallback.
src/​Mvc/​Mvc.Core/​test/​Formatters/​AcceptHeaderParserTest.cs Tests the StringValues overload with multiple, null, and empty values.
src/​Mvc/​Mvc.Core/​src/​Infrastructure/​DefaultOutputFormatterSelector.cs Optimizes media-type storage and formatter iteration.
src/​Mvc/​Mvc.Core/​src/​Formatters/​TextOutputFormatter.cs Returns an empty array when Accept-Charset is absent.
src/​Mvc/​Mvc.Core/​src/​Formatters/​AcceptHeaderParser.cs Adds a boxing-free overload sharing the existing parsing logic.

Review effort: Balanced

davidfowl and others added 2 commits October 31, 2026 07:00
…n benchmark

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Member Author

CI failure is unrelated to this change: the only failing test was Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Tests.QuicStreamContextTests.BidirectionalStream_MultipleStreamsOnConnection_ReusedFromPool (Kestrel QUIC transport, not touched by this PR), which Build Analysis reports with a ~1.16% historical failure rate (build 1657471; 86,595 other tests passed). Retriggered aspnetcore-ci with an empty commit 588699d.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Member Author

The re-run failed on another unrelated test: BlazorTemplates.Tests.BlazorWebTemplateTest.BlazorWebTemplate_ConditionalPasskeyRegistration (Templates.Blazor.Tests, Windows Server x64 platform tests; failed after 5 attempts). Build Analysis reports a ~7.78% historical failure rate for it (build 1657545), and this PR only changes MVC content negotiation (DefaultOutputFormatterSelector, AcceptHeaderParser, TextOutputFormatter). The previous Kestrel QUIC failure did not reproduce. Retriggered aspnetcore-ci with an empty commit d26d6de.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

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 pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants