Skip to content

perf: faster client hints cache, move tests to Microsoft.Testing.Platform - #19

Merged
BenjaminAbt merged 1 commit into
mainfrom
feature/net11-mtp-perf
Nov 21, 2026
Merged

BenjaminAbt merged 1 commit into
mainfrom
feature/net11-mtp-perf

Conversation

@BenjaminAbt

Copy link
Copy Markdown
Member

Summary

This PR does three things:

  1. It makes the cached GetClientHints(HttpContext) path faster. Cache hits take about half the time on .NET 11, and cache misses are 13% faster.
  2. It moves the build from a .NET 11 preview SDK to the stable .NET SDK 11.0.100, and the tests from VSTest to Microsoft.Testing.Platform.
  3. It reworks the benchmarks so that they measure the public API scenarios that matter. The README shows the current benchmark results.

The public API is unchanged. There is one behavior change in the HttpContext.Items cache key, described under "Notes for reviewers".

Changes

Library

HttpClientHintsHttpContextExtensions (MyCSharp.HttpClientHints.AspNetCore)

  • GetClientHints(HttpContext) caches the snapshot under a private static readonly object key instead of the string "__HttpClientHints".
    • The cache can no longer collide with an application entry that uses the same string.
    • HttpContext.Items uses reference hashing and equality for the key instead of hashing and comparing a 17-character string.
    • The method reads HttpContext.Items once per call instead of twice on a cache miss.

HttpClientHintsView (MyCSharp.HttpClientHints.AspNetCore)

  • All properties read their header through one private GetFirstValue(string key) helper, instead of repeating TryGetValue and FirstOrNull in each property.
  • The helper reads the first value through the StringValues indexer and returns null when the header is missing or has no values. Returned values are unchanged, including null and empty first values.

HttpClientHintsInterpreter.IsMobile (MyCSharp.HttpClientHints)

  • The method uses the list pattern ['?', char flag] instead of two ordinal string comparisons. It still returns true only for ?1, false only for ?0, and null for everything else.

Package dependencies

  • On net11.0, MyCSharp.HttpClientHints no longer references the Microsoft.Extensions.Primitives package, because the .NET 11 shared framework (Microsoft.NETCore.App) includes it.
  • net8.0, net9.0, and net10.0 keep the dependency on version 8.0.0, so consumers do not have to update Microsoft.Extensions.Primitives.

Build and dependencies

  • global.json selects the stable SDK 11.0.100 instead of 11.0.100-preview.2.26159.112, with rollForward: latestFeature and allowPrerelease: false. It also selects Microsoft.Testing.Platform as the test runner for dotnet test.
  • LangVersion is 14.0 for net8.0 through net10.0 and 15.0 for net11.0, instead of preview.
  • Test dependencies are now xunit.v3 4.0.3, Microsoft.Testing.Extensions.TrxReport, and Microsoft.Testing.Extensions.CodeCoverage. This PR removes Microsoft.NET.Test.Sdk, xunit.runner.visualstudio, xunit.runner.console, xunit.v3.extensibility.core, xunit.v3.assert, NSubstitute, NSubstitute.Analyzers.CSharp, and Microsoft.Extensions.Diagnostics.Testing.
  • Analyzers are updated: Roslynator 4.14.0 to 5.0.1 and Meziantou.Analyzer 2.0.212 to 3.0.341. The explicit Microsoft.CodeAnalysis.CSharp, Microsoft.CodeAnalysis.Common, and Microsoft.CodeAnalysis.CSharp.Workspaces references are removed.
  • BenchmarkDotNet is updated from 0.15.2 to 0.16.0-preview.2. BenchmarkDotNet.Diagnostics.Windows is removed.
  • The sample project sets WarnOnPackingNonPackableProject to false, so packing the solution does not warn about the non-packable sample.

CI

  • build-and-test.yml runs dotnet test in Microsoft.Testing.Platform mode and writes TRX files per test module: --results-directory TestResults --results-directory-layout per-module -- --report-trx. The test result artifact is named test-results.
  • pr-validation.yml runs one job instead of four. The reusable workflow already installs .NET 8, 9, 10, and 11 by default, and dotnet test runs every test project on net8.0, net9.0, net10.0, and net11.0.

Justfile

  • The default target framework is net11.0.
  • test, test-cov, and test-filter use Microsoft.Testing.Platform syntax. test-cov uses --coverage --coverage-output-format cobertura instead of Coverlet properties, and test-filter uses --filter-query.
  • bench passes its arguments to BenchmarkDotNet after --.

Tests

  • GetClientHintsView_UsesOnlyTheFirstValue covers multiple values, a null first value, and an empty value.
  • GetClientHints_ReusesSnapshotForTheSameContext checks that repeated calls return the same snapshot, that the view still reads live headers, and that an application entry under "__HttpClientHints" stays untouched.
  • UseHttpClientHints_AddsMiddlewareAndReturnsApplicationBuilder runs a real ApplicationBuilder pipeline and checks the Accept-CH response header, instead of only checking the returned NSubstitute mock.
  • IsMobile gains test cases for ?, ?2, ?10, and !1.

Benchmarks

  • The benchmark class measures five scenarios: reading four view properties, building a snapshot with all Client Hints, building a snapshot with only User-Agent, building and caching a snapshot on a cache miss, and returning a cached snapshot.
  • The snapshot benchmarks return the snapshot instead of computing a hash over its properties.
  • The fixed SimpleJob attributes for .NET 8, 9, and 10 are removed. The benchmarks run on the runtime selected with -f.
  • The cache-miss benchmark clears HttpContext.Items before each call, because the cache key is no longer accessible from outside the library.

Documentation

  • The README gains a build and test section and shows the current benchmark output for .NET 11.
  • The link to the ASP.NET Core MVC sample is fixed. It pointed to a folder that does not exist in the repository.

Notes for reviewers

  • Cache key behavior change: Code that read the undocumented HttpContext.Items["__HttpClientHints"] entry no longer finds the snapshot there. GetClientHints(HttpContext) is the supported way to read it.
  • GetFirstValue uses the indexer on purpose: A side-by-side benchmark of an alternative that used StringValues.Enumerator measured it 15% slower on average than the original code on .NET 11 when building a snapshot with all Client Hints. Its standard deviation was 10.7 ns instead of about 2 ns.
  • C# 14 on older targets: net8.0 through net10.0 compile with C# 14, which the library already needed for the field keyword in HttpClientHintsMiddlewareConfig.
  • BenchmarkDotNet preview: The benchmark project uses BenchmarkDotNet 0.16.0-preview.2. It is not part of the NuGet packages.

Testing

  • dotnet build -c Release: 0 warnings, 0 errors, with TreatWarningsAsErrors enabled.
  • dotnet test -c Release --no-build --results-directory TestResults --results-directory-layout per-module -- --report-trx, the same command as CI: 112 tests passed, 28 per target framework on net8.0, net9.0, net10.0, and net11.0.
  • dotnet format --verify-no-changes on src/, tests/, and perf/: no changes.
  • dotnet pack: the MyCSharp.HttpClientHints package depends on Microsoft.Extensions.Primitives 8.0.0 for net8.0, net9.0, and net10.0, and has no dependencies for net11.0.

Benchmark

The Release benchmarks compare the original library source at cc8df89 with this PR. Both versions used the same benchmark project and build configuration on an AMD Ryzen 9 9950X running Windows 10 x64, with .NET SDK 11.0.100, .NET 11.0.0, and BenchmarkDotNet 0.16.0-preview.2. The error is half the width of BenchmarkDotNet's 99.9% confidence interval.

Scenario Before, mean ± error After, mean ± error Change Allocated per operation, both versions
Read four properties from the view 19.02 ± 0.38 ns 18.69 ± 0.30 ns Within measurement error 0 B
Build a snapshot with all Client Hints 58.23 ± 1.10 ns 58.70 ± 0.76 ns Within measurement error 88 B
Build a snapshot with only User-Agent 51.90 ± 0.67 ns 51.31 ± 0.85 ns Within measurement error 88 B
Build and cache a snapshot on a cache miss 88.15 ± 1.21 ns 76.25 ± 2.83 ns 13% faster 88 B
Retrieve a cached snapshot 12.63 ± 0.38 ns 6.17 ± 0.11 ns 51% faster 0 B

The cache scenarios are faster because of the new HttpContext.Items key described above. The cache-miss benchmark clears an existing HttpContext.Items dictionary before each call. The cache-hit benchmark uses a pre-populated context. The results measure library calls against ASP.NET Core's HeaderDictionary and DefaultHttpContext.

On .NET 8.0.34, cache hits went from 15.10 ns to 10.10 ns (33% faster) and cache misses from 108.44 ns to 96.46 ns (11% faster). Building a snapshot is 7% faster with all Client Hints and 8% faster with only User-Agent. Reading four properties is within measurement error.

Reproduce

dotnet run --project perf/HttpClientHints.Benchmarks -c Release -f net11.0 -- --filter '*' --warmupCount 6 --iterationCount 15 --iterationTime 200 --launchCount 2

For .NET 8, replace -f net11.0 with -f net8.0.

To measure the baseline, run the same command in a second copy of the repository after restoring the three changed library source files from cc8df89:

git checkout cc8df89 -- src/HttpClientHints/HttpClientHintsInterpreter.cs src/HttpClientHints.AspNetCore/HttpClientHintsHttpContextExtensions.cs src/HttpClientHints.AspNetCore/HttpClientHintsView.cs

Keep the project files, SDK selection, and package versions from this PR in both copies. Restoring all of src/ from cc8df89 fails with NU1010, because the original HttpClientHints.csproj also references Microsoft.Extensions.Primitives for net11.0.

Raw benchmark output

.NET 11, baseline at cc8df89
BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update)
AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores
Memory: 61,64 GB Total, 31,92 GB Available
.NET SDK 11.0.100
  [Host]     : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4
  Job-ZRYWOI : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4

IterationCount=15  IterationTime=200ms  LaunchCount=2
WarmupCount=6
Method Mean Error StdDev Gen0 Allocated
ReadViewProperties 19.02 ns 0.378 ns 0.531 ns - -
GetClientHintsFromHeaders 58.23 ns 1.097 ns 1.573 ns 0.0051 88 B
GetClientHintsFromHeadersWithoutHints 51.90 ns 0.668 ns 0.937 ns 0.0052 88 B
GetClientHintsFromContextUncached 88.15 ns 1.214 ns 1.701 ns 0.0053 88 B
GetClientHintsFromContextCached 12.63 ns 0.381 ns 0.558 ns - -
.NET 11, this PR
BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update)
AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores
Memory: 61,64 GB Total, 31,83 GB Available
.NET SDK 11.0.100
  [Host]     : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4
  Job-ZRYWOI : .NET 11.0.0 (11.0.0, 11.0.26.53018), X64 RyuJIT x86-64-v4

IterationCount=15  IterationTime=200ms  LaunchCount=2
WarmupCount=6
Method Mean Error StdDev Gen0 Allocated
ReadViewProperties 18.688 ns 0.2959 ns 0.4337 ns - -
GetClientHintsFromHeaders 58.697 ns 0.7625 ns 1.1176 ns 0.0051 88 B
GetClientHintsFromHeadersWithoutHints 51.311 ns 0.8545 ns 1.2255 ns 0.0052 88 B
GetClientHintsFromContextUncached 76.252 ns 2.8269 ns 4.0542 ns 0.0050 88 B
GetClientHintsFromContextCached 6.174 ns 0.1132 ns 0.1623 ns - -
.NET 8.0.34, baseline at cc8df89
BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update)
AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores
Memory: 61,64 GB Total, 31,76 GB Available
.NET SDK 11.0.100
  [Host]     : .NET 8.0.34 (8.0.34, 8.0.3426.52217), X64 RyuJIT x86-64-v4
  Job-ZRYWOI : .NET 8.0.34 (8.0.34, 8.0.3426.52217), X64 RyuJIT x86-64-v4

IterationCount=15  IterationTime=200ms  LaunchCount=2
WarmupCount=6
Method Mean Error StdDev Gen0 Allocated
ReadViewProperties 30.67 ns 0.478 ns 0.670 ns - -
GetClientHintsFromHeaders 76.53 ns 1.015 ns 1.423 ns 0.0051 88 B
GetClientHintsFromHeadersWithoutHints 68.10 ns 0.721 ns 1.033 ns 0.0051 88 B
GetClientHintsFromContextUncached 108.44 ns 1.634 ns 2.291 ns 0.0053 88 B
GetClientHintsFromContextCached 15.10 ns 0.151 ns 0.217 ns - -
.NET 8.0.34, this PR
BenchmarkDotNet v0.16.0-preview.2, Windows 10 (10.0.19045.7846/22H2/2022Update)
AMD Ryzen 9 9950X 4.30GHz, 1 CPU, 32 logical and 16 physical cores
Memory: 61,64 GB Total, 22,8 GB Available
.NET SDK 11.0.100
  [Host]     : .NET 8.0.34 (8.0.34, 8.0.3426.52217), X64 RyuJIT x86-64-v4
  Job-ZRYWOI : .NET 8.0.34 (8.0.34, 8.0.3426.52217), X64 RyuJIT x86-64-v4

IterationCount=15  IterationTime=200ms  LaunchCount=2
WarmupCount=6
Method Mean Error StdDev Gen0 Allocated
ReadViewProperties 31.46 ns 0.576 ns 0.788 ns - -
GetClientHintsFromHeaders 71.45 ns 0.838 ns 1.175 ns 0.0050 88 B
GetClientHintsFromHeadersWithoutHints 62.95 ns 1.121 ns 1.678 ns 0.0051 88 B
GetClientHintsFromContextUncached 96.46 ns 1.868 ns 2.680 ns 0.0051 88 B
GetClientHintsFromContextCached 10.10 ns 0.188 ns 0.282 ns - -

…form

- Cache the HttpContext snapshot under a private object key instead of
  the string "__HttpClientHints"
- Read headers in HttpClientHintsView through one GetFirstValue helper
- Use a list pattern in HttpClientHintsInterpreter.IsMobile
- Drop the Microsoft.Extensions.Primitives package dependency for net11.0
- Build with the stable .NET SDK 11.0.100 and LangVersion 14/15
- Run tests on Microsoft.Testing.Platform with xunit.v3 4, TRX and coverage
- Validate PRs in one job across net8.0 to net11.0
- Rework the benchmark scenarios and show the current results in the README
@BenjaminAbt
BenjaminAbt merged commit 41a991b into main Nov 21, 2026
1 check passed
@BenjaminAbt
BenjaminAbt deleted the feature/net11-mtp-perf branch November 21, 2026 14:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant