Repository navigation
Conversation
ReadAsStringAsync allocated a StreamReader (1 KB byte buffer, ~2 KB char buffer, decoder and StringBuilder) for every section, which FormFeature calls for every multipart text field. When the body is our own MultipartReaderStream, read into a pooled 1 KB buffer and, if the value fits, decode it directly. Plain UTF-8 without a possible BOM uses Encoding.UTF8.GetString, which is exactly what StreamReader produces; anything else is decoded by a StreamReader over the same bytes. Values larger than the buffer continue through a StreamReader that first replays the consumed bytes, so results are unchanged. Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
The buffered fast path can ignore an already-canceled token and consume the section, regressing cancellation behavior unless cancellation is explicitly checked before reading.
1 open issue
What changed in this PR
Reduces allocations when reading small multipart form values by avoiding a StreamReader on the common UTF-8 path used by MultipartReader and FormFeature.
Changes:
- Adds pooled-buffer decoding with
StreamReaderfallbacks for possible byte-order marks, other encodings, and larger values. - Adds compatibility tests covering encodings, buffer boundaries, and consecutive sections.
- Adds form-reading benchmarks for URL-encoded and multipart requests.
| File | Description |
|---|---|
| src/Http/WebUtilities/test/MultipartSectionStreamExtensionsTests.cs | Tests decoding compatibility and consecutive-section reads. |
| src/Http/WebUtilities/src/MultipartSectionStreamExtensions.cs | Adds the pooled-buffer fast path and fallback stream wrapper. |
| src/Http/Http/perf/Microbenchmarks/FormFeatureReadFormBenchmarks.cs | Benchmarks form-reading performance and allocations. |
Review effort: Balanced
| var length = 0; | ||
| while (length < buffer.Length) | ||
| { | ||
| var read = await section.Body.ReadAsync(buffer.AsMemory(length), cancellationToken); |
There was a problem hiding this comment.
I checked this against main, and the current implementation does not reject an already-canceled token for a buffered section either.
I added this test temporarily and ran it with main's MultipartSectionStreamExtensions.cs:
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReadAsStringAsync_CanceledToken_Throws(bool seekable)
{
var section = await ReadSingleSectionAsync("value"u8.ToArray(), contentType: null, seekable);
await Assert.ThrowsAsync<OperationCanceledException>(async () => await section.ReadAsStringAsync(new CancellationToken(canceled: true)));
}On main, both cases fail with Assert.Throws() Failure: No exception was thrown. StreamReader.ReadToEndAsync(cancellationToken) only passes the token through to Stream.ReadAsync, and MultipartReaderStream.ReadAsync returns already-buffered data without checking it. This PR has the same result: the value is returned. Adding ThrowIfCancellationRequested() would therefore be a behavior change, which this PR intends to avoid, so I'm leaving the code as is. I'm leaving this thread open for a maintainer to decide.
🤖 Posted by ASP.NET Core Perf 2 (AI Agent)
|
Heads-up for reviewers: this PR overlaps with #70164, which was opened earlier from the same account and targets the same 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
4e349cf to
fd7b512
Compare
Co-authored-by: Copilot <[email protected]>
|
Retriggered CI with an empty commit (fd17e7e). The previous run failed only the Blazor E2E test Note: a malformed retrigger commit (4e349cf) was pushed by mistake for under a minute and force-reverted to fd7b512 before the empty commit was added. The PR diff is unchanged (3 files). 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
CI update:
The same pipeline is failing on 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |

MultipartSectionStreamExtensions.ReadAsStringAsynccreates a newStreamReaderfor every section: a 1 KB byte buffer, a ~2 KB char buffer, a decoder and aStringBuilderinReadToEndAsync, about 3.5 KB in total.FormFeaturecalls it for every multipart text field, so a form with a few fields allocates more on these readers than on anything else.With this change, when
section.Bodyis our own internalMultipartReaderStream(the case forMultipartReader/FormFeature), the value is read into anArrayPoolbuffer of 1 KB, the same size as the old StreamReader buffer:EF/FE/FF/00): returnsEncoding.UTF8.GetString. This is exactly whatStreamReaderproduces, including U+FFFD replacement for invalid or truncated sequences, becauseStreamReaderflushes the decoder at EOF.StreamReaderover aMemoryStreamof the same bytes, so the result is unchanged by construction.StreamReaderover a small private stream that replays the already-read bytes and then the rest of the section.The pooled buffer is only passed to
MultipartReaderStream, which copies into it from its own buffer and does not keep it. The buffer is returned infinally. Any otherBodystream type takes the existing code path unchanged.Benchmark
FormFeatureReadFormBenchmarks(added):DefaultHttpContext+ReadFormAsync, BenchmarkDotNet InProcess, 3 interleaved rounds:Tests
Added
MultipartSectionStreamExtensionsTests, which comparesReadAsStringAsyncwith the previousStreamReaderimplementation on the same bytes. Inputs are read through aMultipartReader(seekable and non-seekable) and also as a plainBodystream. Cases cover:charset=utf-16,iso-8859-1andutf-8These tests pass on main and on this branch. When the BOM guard is mutated, 6 cases fail. WebUtilities (581) and Http (258) tests pass.