Repository navigation
perf: faster client hints cache, move tests to Microsoft.Testing.Platform - #19
Merged
Merged
Conversation
…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
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
This PR does three things:
GetClientHints(HttpContext)path faster. Cache hits take about half the time on .NET 11, and cache misses are 13% faster.The public API is unchanged. There is one behavior change in the
HttpContext.Itemscache key, described under "Notes for reviewers".Changes
Library
HttpClientHintsHttpContextExtensions(MyCSharp.HttpClientHints.AspNetCore)GetClientHints(HttpContext)caches the snapshot under a privatestatic readonly objectkey instead of the string"__HttpClientHints".HttpContext.Itemsuses reference hashing and equality for the key instead of hashing and comparing a 17-character string.HttpContext.Itemsonce per call instead of twice on a cache miss.HttpClientHintsView(MyCSharp.HttpClientHints.AspNetCore)GetFirstValue(string key)helper, instead of repeatingTryGetValueandFirstOrNullin each property.StringValuesindexer and returnsnullwhen the header is missing or has no values. Returned values are unchanged, includingnulland empty first values.HttpClientHintsInterpreter.IsMobile(MyCSharp.HttpClientHints)['?', char flag]instead of two ordinal string comparisons. It still returnstrueonly for?1,falseonly for?0, andnullfor everything else.Package dependencies
net11.0,MyCSharp.HttpClientHintsno longer references theMicrosoft.Extensions.Primitivespackage, because the .NET 11 shared framework (Microsoft.NETCore.App) includes it.net8.0,net9.0, andnet10.0keep the dependency on version 8.0.0, so consumers do not have to updateMicrosoft.Extensions.Primitives.Build and dependencies
global.jsonselects the stable SDK 11.0.100 instead of11.0.100-preview.2.26159.112, withrollForward: latestFeatureandallowPrerelease: false. It also selects Microsoft.Testing.Platform as the test runner fordotnet test.LangVersionis14.0fornet8.0throughnet10.0and15.0fornet11.0, instead ofpreview.xunit.v34.0.3,Microsoft.Testing.Extensions.TrxReport, andMicrosoft.Testing.Extensions.CodeCoverage. This PR removesMicrosoft.NET.Test.Sdk,xunit.runner.visualstudio,xunit.runner.console,xunit.v3.extensibility.core,xunit.v3.assert,NSubstitute,NSubstitute.Analyzers.CSharp, andMicrosoft.Extensions.Diagnostics.Testing.Microsoft.CodeAnalysis.CSharp,Microsoft.CodeAnalysis.Common, andMicrosoft.CodeAnalysis.CSharp.Workspacesreferences are removed.BenchmarkDotNet.Diagnostics.Windowsis removed.WarnOnPackingNonPackableProjecttofalse, so packing the solution does not warn about the non-packable sample.CI
build-and-test.ymlrunsdotnet testin 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 namedtest-results.pr-validation.ymlruns one job instead of four. The reusable workflow already installs .NET 8, 9, 10, and 11 by default, anddotnet testruns every test project onnet8.0,net9.0,net10.0, andnet11.0.Justfile
net11.0.test,test-cov, andtest-filteruse Microsoft.Testing.Platform syntax.test-covuses--coverage --coverage-output-format coberturainstead of Coverlet properties, andtest-filteruses--filter-query.benchpasses its arguments to BenchmarkDotNet after--.Tests
GetClientHintsView_UsesOnlyTheFirstValuecovers multiple values, anullfirst value, and an empty value.GetClientHints_ReusesSnapshotForTheSameContextchecks that repeated calls return the same snapshot, that the view still reads live headers, and that an application entry under"__HttpClientHints"stays untouched.UseHttpClientHints_AddsMiddlewareAndReturnsApplicationBuilderruns a realApplicationBuilderpipeline and checks theAccept-CHresponse header, instead of only checking the returned NSubstitute mock.IsMobilegains test cases for?,?2,?10, and!1.Benchmarks
User-Agent, building and caching a snapshot on a cache miss, and returning a cached snapshot.SimpleJobattributes for .NET 8, 9, and 10 are removed. The benchmarks run on the runtime selected with-f.HttpContext.Itemsbefore each call, because the cache key is no longer accessible from outside the library.Documentation
Notes for reviewers
HttpContext.Items["__HttpClientHints"]entry no longer finds the snapshot there.GetClientHints(HttpContext)is the supported way to read it.GetFirstValueuses the indexer on purpose: A side-by-side benchmark of an alternative that usedStringValues.Enumeratormeasured 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.net8.0throughnet10.0compile with C# 14, which the library already needed for thefieldkeyword inHttpClientHintsMiddlewareConfig.Testing
dotnet build -c Release: 0 warnings, 0 errors, withTreatWarningsAsErrorsenabled.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 onnet8.0,net9.0,net10.0, andnet11.0.dotnet format --verify-no-changesonsrc/,tests/, andperf/: no changes.dotnet pack: theMyCSharp.HttpClientHintspackage depends onMicrosoft.Extensions.Primitives8.0.0 fornet8.0,net9.0, andnet10.0, and has no dependencies fornet11.0.Benchmark
The Release benchmarks compare the original library source at
cc8df89with 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.The cache scenarios are faster because of the new
HttpContext.Itemskey described above. The cache-miss benchmark clears an existingHttpContext.Itemsdictionary before each call. The cache-hit benchmark uses a pre-populated context. The results measure library calls against ASP.NET Core'sHeaderDictionaryandDefaultHttpContext.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 2For .NET 8, replace
-f net11.0with-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:Keep the project files, SDK selection, and package versions from this PR in both copies. Restoring all of
src/fromcc8df89fails withNU1010, because the originalHttpClientHints.csprojalso referencesMicrosoft.Extensions.Primitivesfornet11.0.Raw benchmark output
.NET 11, baseline at
cc8df89.NET 11, this PR
.NET 8.0.34, baseline at
cc8df89.NET 8.0.34, this PR