Repository navigation
Reuse a cached StringBuilder when formatting header values - #70203
Conversation
Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues are recorded for the header-formatting allocation changes.
No open issues 🎉
What changed in this PR
Reduces allocations when formatting typed HTTP headers by reusing a bounded, thread-local StringBuilder, while preserving existing output and public APIs.
Changes:
- Adds a shared builder cache and uses it across six header-formatting implementations.
- Formats Content-Disposition in one builder and avoids intermediate numeric strings in Cache-Control and Content-Range.
- Adds formatting regression tests and allocation benchmarks.
| File | Description |
|---|---|
src/Http/Http/perf/Microbenchmarks/HeaderValueToStringBenchmarks.cs |
Adds timing and allocation benchmarks for common headers. |
src/Http/Headers/test/HeaderValueToStringTest.cs |
Tests sequential formatting, large values, disposition output, and invariant numbers. |
src/Http/Headers/src/StringBuilderCache.cs |
Adds a thread-local cache retaining builders up to 360 characters in capacity. |
src/Http/Headers/src/RangeHeaderValue.cs |
Reuses the cached builder for range formatting. |
src/Http/Headers/src/NameValueHeaderValue.cs |
Reuses the cached builder for name-value list formatting. |
src/Http/Headers/src/MediaTypeHeaderValue.cs |
Reuses the cached builder for media types and parameters. |
src/Http/Headers/src/ContentRangeHeaderValue.cs |
Reuses the builder and formats invariant numbers directly into it. |
src/Http/Headers/src/ContentDispositionHeaderValue.cs |
Formats the disposition and parameters into one cached builder. |
src/Http/Headers/src/CacheControlHeaderValue.cs |
Reuses the builder and eliminates intermediate numeric strings. |
Review effort: Balanced
|
CI update:
The same failures are hitting other unrelated PRs (#70182, #70196, #70198), and the pipeline is failing on 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
CI status for current head The same leg also fails on This PR changes only 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
/review |
Co-authored-by: Copilot <[email protected]>
|
Retriggered CI with an empty commit. The only failing check was 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
Copy System.Text.StringBuilderCache from dotnet/runtime into src/Shared/System.Text (same namespace, file-scoped), use it from Microsoft.Net.Http.Headers and add unit tests. Co-authored-by: Copilot <[email protected]>
DeagleGross
left a comment
There was a problem hiding this comment.
Ideally we should move runtime's StringBuilderCache into shared to not have duplicate code. I'll do it separately
|
✅ No documentation PR was created. Confidence that documentation is needed: 5% No docs needed: internal performance refactoring (cached StringBuilder for header formatting) with no public API, default, or output changes. Documentation surfaces considered
|
Reuse a cached StringBuilder when formatting header values
Fewer allocations when formatting typed header values with ToString.
Description
Formatting typed header values (
CacheControlHeaderValue,MediaTypeHeaderValue,ContentDispositionHeaderValue,ContentRangeHeaderValue,RangeHeaderValue,NameValueHeaderValue.ToString(list)) allocated a freshStringBuilderper call. These run on common response paths:ResponseHeaders.CacheControl/ContentDisposition/ContentRangesetters, file results with range processing, and OutputCaching/ResponseCaching.Changes
System.Text.StringBuilderCache, copied from dotnet/runtime (src/libraries/Common/src/System/Text/StringBuilderCache.cs) intosrc/Shared/System.Text/StringBuilderCache.cswith the same namespace. The only change is a file-scoped namespace for this repo's analyzers. It keeps one[ThreadStatic]builder per thread and reuses it only when capacity ≤ 360 chars. The builder never leaves the formatting method. Only the resultingstringis returned, and the builder is cleared on acquire, so nothing cached is reachable by callers or shared between requests. A nested acquire just gets a new builder.StringBuilderCacheTestin Shared.Tests covers it.ContentDispositionHeaderValue.ToStringbuilds into a single builder instead of concatenating_dispositionTypewith a separately built parameter string.CacheControlHeaderValue/ContentRangeHeaderValueusesAppend(NumberFormatInfo.InvariantInfo, $"...")instead of an intermediateToString(InvariantInfo)string. Output is still invariant.No public API or output changes. The new
HeaderValueToStringTestcovers:NegativeSign.It passes on both
mainand this branch.Benchmarks
HeaderValueToStringBenchmarks(new, insrc/Http/Http/perf/Microbenchmarks), re-run on e614f41 with the runtimeStringBuilderCache. The baseline is the merge base4f556f73a6plus the benchmark file, on the same SDK. Runs were interleaved (base, PR, base, PR), with--config perflab --warmupCount 3 --iterationCount 15:text/html; charset=utf-8)attachment+SetHttpFileName)bytes 0-1023/1048576)public, max-age=31536000no-cache, no-store, must-revalidateprivate, max-age=60, s-maxage=120Tests
Microsoft.Net.Http.Headers.Tests: 1825 passed, on both main and the PR.Microsoft.AspNetCore.Shared.Tests: 1374 passed (includes the 7 newStringBuilderCacheTesttests).Microsoft.AspNetCore.Http.Results.Tests: 1067 passed.🤖 Posted by ASP.NET Core Perf 2 (AI Agent)