Skip to content

Avoid StringBuilder when encoding Content-Disposition file names - #70204

Merged
DeagleGross merged 2 commits into
mainfrom
perf/http-contentdisposition-encode5987
Nov 11, 2026
Merged

DeagleGross merged 2 commits into
mainfrom
perf/http-contentdisposition-encode5987

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Avoid StringBuilder when encoding Content-Disposition file names

  • 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.

Fewer allocations when encoding Content-Disposition filename* values.

Description

ContentDispositionHeaderValue.SetHttpFileName runs for every file result with a download name (Results.File(..., fileDownloadName: ...), MVC FileResult, via FileResultHelper). It always computes filename* with Encode5987. That method built the value with a StringBuilder, appending each percent-encoded byte through an interpolated-string append. Quoting a non-token filename also went through string.Format(CultureInfo.InvariantCulture, "\"{0}\"", segment), which boxes the StringSegment.

Changes

  • Encode5987: compute the exact output length first. Each non-attr-char rune adds Utf8SequenceLength * 3, and invalid surrogates count as U+FFFD, matching Rune.DecodeFromUtf16. Then:
    • if nothing needs encoding, return string.Concat("UTF-8''", value);
    • otherwise, write the string once with string.Create.
  • The UTF-8 bit math in EncodeToUtf8Hex is unchanged; it now writes %XX directly into the destination span.
  • EncodeAndQuoteMime: string.Concat("\"", value, "\"") replaces string.Format.

The output is identical. New tests assert the full header string for:

  • ASCII, spaces, and quote/backslash escaping;
  • 2-, 3- and 4-byte UTF-8;
  • lone high and low surrogates.

They pass on main and on this branch. The existing FileNameStar_WhenNeedsEncoding_UsesHex covers every ASCII byte.

Benchmarks

ContentDispositionSetFileNameBenchmarks (new): new ContentDispositionHeaderValue("attachment") + SetHttpFileName(name) + ToString(), the same sequence FileResultHelper runs. 3 interleaved main/PR rounds:

Method main (ns, r1/r2/r3) PR (ns, r1/r2/r3) main alloc PR alloc
AsciiFileName (report-2024.pdf) 310.0 / 308.4 / 302.5 243.6 / 270.4 / 276.3 1,208 B 1,000 B
FileNameWithSpaces (Quarterly Report 2024.pdf) 523.3 / 536.5 / 520.1 422.4 / 421.3 / 408.8 1,840 B 1,464 B

Tests

  • Microsoft.Net.Http.Headers.Tests: 1828 passed.
  • The new ContentDisposition tests also pass on main.

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

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 18:46
@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions 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.

🔵 Needs a closer look

Missing frozen base/head identities and an existing-feedback snapshot prevented completion of revision-provenance and feedback-deduplication checks.

No open issues 🎉

What changed in this PR

This PR reduces allocations when formatting Content-Disposition download filenames used by HTTP and MVC file results, while preserving the existing encoding behavior.

Changes:

  • Replace StringBuilder encoding with exact-length calculation and direct writes through string.Create, plus a fast path for unencoded values.
  • Use span-based concatenation to quote filenames without boxing.
  • Add full-header formatting tests and benchmarks for ASCII filenames and filenames containing spaces.
File Description
src/​Http/​Http/​perf/​Microbenchmarks/​ContentDispositionSetFileNameBenchmarks.cs Adds benchmarks for filename assignment and header serialization.
src/​Http/​Headers/​test/​ContentDispositionHeaderValueTest.cs Covers escaping, multibyte UTF-8, and lone-surrogate replacement.
src/​Http/​Headers/​src/​ContentDispositionHeaderValue.cs Removes builder-based encoding and boxing during filename quoting.

Review effort: Balanced

@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
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@DeagleGross

Copy link
Copy Markdown
Member

I think for bigger perf change we would want to avoid stringSegment completely. Vibe-generated a public API proposal which I'll review and update later:
#70435

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 10, 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 10, 2026
@DeagleGross
DeagleGross merged commit b0b2587 into main Nov 11, 2026
30 checks passed
@DeagleGross
DeagleGross deleted the perf/http-contentdisposition-encode5987 branch November 11, 2026 09:11
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 3%

No docs needed: perf-only refactor (source, tests, benchmark files) with identical output.

Documentation surfaces considered

  • Conceptual article: Not required — Internal allocation optimization in ContentDispositionHeaderValue; no public API or behavior change.
  • Migration guidance: Not required — No action needed by users upgrading.
  • Breaking change: Not required — Output is identical; no compatibility impact.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — d87bb001 Deployed Nov 11, 2026 by DeagleGross via conclusion #290
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants