Skip to content

Allocate a component's second RenderTreeBuilder on demand - #70153

Open
davidfowl wants to merge 2 commits into
mainfrom
perf/components-lazy-next-render-tree
Open

davidfowl wants to merge 2 commits into
mainfrom
perf/components-lazy-next-render-tree

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Allocate a component's second RenderTreeBuilder only when it re-renders

Description

ComponentState eagerly creates two RenderTreeBuilders, each with its own RenderTreeFrameArrayBuilder and Stack<int>, so it can diff new output against the previous output. Many components only ever render once, and every component does during static SSR, so the second builder is never used. It stays allocated and retained for the component's lifetime, which in a Blazor Server circuit can be long.

  • _nextRenderTree is now created only when a component re-renders.
  • A component's first render is written directly into CurrentRenderTree (which is empty at that point) and diffed against an empty ArrayRange.
  • If the first render throws, either from the render fragment or from AssertTreeIsValid, CurrentRenderTree is cleared. It keeps representing the previous (empty) output, as before.
  • From the second render onward, behaviour is the same as today.

Benchmarks

This adds the same HtmlRendererBenchmark as #70151, with identical files. RenderAndWriteHtml creates an HtmlRenderer, renders 101 components (a 100-row table whose rows are child components), and writes the HTML.

Local BenchmarkDotNet, InProcess, 3 interleaved rounds against main:

main PR
RenderAndWriteHtml allocated 141 KB 129 KB (−8.5%)
RenderAndWriteHtml time 110.9 / 106.0 / 105.1 µs 102.5 / 114.0 / 106.5 µs (neutral, within noise)
Retained memory per rendered component (GC.GetTotalMemory(true) with 50 live renderers) −127 B per component

Tests

  • Microsoft.AspNetCore.Components.Tests: 1305 passed, 8 skipped.
  • New tests:
    • ExceptionDuringFirstRender_LeavesRenderTreeEmpty_AndLaterRenderSucceeds
    • InvalidRenderTreeDuringFirstRender_LeavesRenderTreeEmpty
  • Microsoft.AspNetCore.Components.Web.Tests: 330 passed.
  • Microsoft.AspNetCore.Components.Endpoints.Tests: 883 passed.
  • Microsoft.AspNetCore.Components.Server.Tests: 394 passed.

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

ComponentState eagerly created two RenderTreeBuilders (each with a
RenderTreeFrameArrayBuilder and a Stack<int>) so that it could diff the new
output against the previous one. Many components only ever render once, for
example every component during static SSR, so the second builder was never
used.

Write the first render directly into CurrentRenderTree, diffing it against an
empty tree, and only create the second builder when the component re-renders.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl
davidfowl requested a review from a team as a code owner October 31, 2026 00:44
Copilot AI balanced review requested due to automatic review settings October 31, 2026 00:44
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components 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.

🟢 Approval recommended

No active review issues remain for the change that defers allocation of the second render-tree builder.

No open issues 🎉

What changed in this PR

This PR reduces per-component memory use in Blazor by allocating the second RenderTreeBuilder only when a component renders again, avoiding that allocation for components that render once.

Changes:

  • Writes the first render directly into the current tree and diffs it against an empty tree, preserving subsequent-render behavior.
  • Adds regression tests for first-render failures, empty-tree cleanup, and successful recovery.
  • Adds HTML-rendering benchmarks to measure rendering allocations and HTML-writing performance.
File Description
src/​Components/​Components/​test/​RendererTest.cs Tests first-render failure cleanup and later render recovery.
src/​Components/​Components/​src/​Rendering/​ComponentState.cs Defers the second builder allocation and handles first-render cleanup and nullable disposal.
src/​Components/​Components/​perf/​Microsoft.AspNetCore.Components.Performance.csproj References Components.Web for HTML-rendering benchmarks.
src/​Components/​Components/​perf/​HtmlRendererBenchmark.cs Adds full-render and HTML-writing benchmarks using a component-based table.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

Compliance check: no public API changes. Rendered output, batches and diffs are identical, and first-render exceptions still leave CurrentRenderTree empty (two new tests cover this). For full transparency, there is one theoretical difference. If a component reentrantly reads its own frames (Renderer.GetCurrentRenderTreeFrames(ownId)) from inside its first BuildRenderTree call, it now sees partially built frames instead of an empty range. Nothing in the repo does this; every reader runs after the fragment completes, at which point the tree is the same as before. If maintainers consider that unacceptable, I can close the gap or drop the PR.

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

davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-components-e2e

Rerunning e2e. Both failures are known flaky tests unrelated to this change, per Build Analysis: ServerRoutingTest.NavigationLock_CanBlockExternalNavigation (25.42% historical failure rate) and VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements (8.59%). The same tests also failed on unrelated PRs #70125 and #70139.

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

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-components-e2e

Rerunning e2e. Only the Mono-server leg failed; CoreCLR and Mono/WebAssembly passed with this change. Failing tests, per Build Analysis:

If the QuickGrid test fails again, I'll investigate it as potentially related.

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

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@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
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 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 13, 2026

davidfowl commented Nov 16, 2026 •

Copy link
Copy Markdown
Member Author

Merge assessment

Verdict: Merge after a green aspnetcore-ci rerun and a Components owner review. Every component that renders only once (including every component in static SSR) no longer allocates a second RenderTreeBuilder, and from the second render onward the diff logic is unchanged.

Size S: +39/−9 production lines, +66 test, +119 benchmark; 4 files, 1 shipping assembly (Microsoft.AspNetCore.Components)
Impact Medium: RenderAndWriteHtml (101 components) 141→129 KB (−8.5%); −127 B retained per rendered component; time neutral (102–114 vs 105–111 µs)
Risk Medium: Blazor renderer core (ComponentState.RenderIntoBatch), used by every component render
Tests 2 new tests: an exception thrown and an invalid tree on first render both leave the tree empty, and a later render succeeds; Components, Web, Endpoints and Server suites pass (author-reported)
Review No review from a user with write access; Copilot review recommended approval
CI Green on 85d4697, including all 3 components-e2e legs after 2 reruns for known flakes (NavigationLock_CanBlockExternalNavigation and others); last run 2026-11-06, 469 commits behind main, labeled pending-ci-rerun
Complexity Low-Medium: adds a first-render branch and two failure-path Clear() calls to a hot method
Reversibility Easy; one file
Security sensitivity Not assessed (repo review guidance)
Encoding/escaping parity n/a
Behavior / public API change No public API change. One edge: a component that reads its own frames through Renderer.GetCurrentRenderTreeFrames from inside its first BuildRenderTree now sees partial frames instead of an empty range; no code in the repo does this

Reasons to merge

  • First render diffs against an empty range, which is the same input the old code diffed against.
  • Both first-render failure paths restore the empty tree, and tests cover both.
  • All other readers of CurrentRenderTree in the repo run after the render fragment completes.

Reasons not to merge yet

  • The reentrant self-read edge is observable by third-party Renderer subclasses and needs a Components owner decision.
  • The win is allocation only; time is unchanged.
  • The benchmark files are identical to those in open PR Classify element names once in StaticHtmlRenderer #70151, so whichever PR merges second needs a rebase.

What would change this verdict: A Components owner treating the reentrant self-read as a supported scenario would make this a Hold.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants