Skip to content

Avoid redundant dictionary lookups when diffing keyed items - #70133

Closed
davidfowl wants to merge 3 commits into
mainfrom
perf/components-keyed-diff
Closed

davidfowl wants to merge 3 commits into
mainfrom
perf/components-keyed-diff

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Avoid redundant dictionary lookups when diffing keyed items

Hash each old-tree @key once when building the keyed-item diff lookup

Description

When a sibling range contains @keyed elements or components, RenderTreeDiffBuilder.BuildKeyToInfoLookup builds a Dictionary<object, KeyedItemInfo>. For each old-tree key it called ContainsKey and then the indexer setter, which is two hash lookups. Keys are object, so each lookup costs a virtual GetHashCode/Equals.

This change uses a single TryAdd for old-tree keys. The new-tree pass is unchanged and still uses TryGetValue followed by the indexer. Duplicate-key detection, the exceptions it throws, and the diff output all stay the same. There are no public API or behavior changes.

Update: An earlier revision also used CollectionsMarshal.GetValueRefOrAddDefault in the new-tree pass. That part was removed (95837ac) to comply with a project rule against CollectionsMarshal, MemoryMarshal, Unsafe and stackalloc in these perf changes. Most of the earlier ~8–10% win came from that part. The remaining win is small (~3%), close to the noise on this VM.

Benchmark

The PR adds KeyedListDiffBenchmark in src/Components/Components/perf. It diffs a <ul> with 500 @keyed <li> items, once in the same order and once with a swap, an insert and a removal. Setup: BenchmarkDotNet --config perflab (InProcess) on a 2 vCPU Linux VM, 6 interleaved A/B rounds. Both versions allocate 0 B.

Method main (median of 6) PR (median of 6) Δ
ComputeDiff_KeyedList_SameOrder 29.80 µs 28.55 µs ~−4%
ComputeDiff_KeyedList_Reordered 29.88 µs 29.03 µs ~−3%

Tests

  • Microsoft.AspNetCore.Components.Tests: 1303 passed, 8 skipped. This includes the RenderTreeDiffBuilderTest keyed and duplicate-key cases.

Benchmark (3 interleaved rounds)

KeyedListDiffBenchmark (added in this PR), 500 @keyed items.

Round Benchmark main Mean PR Mean Δ time main Allocated PR Allocated
1 ComputeDiff_KeyedList_SameOrder [ItemCount=500] 30.06 µs 28.33 µs -5.8% 0 B 0 B
1 ComputeDiff_KeyedList_Reordered [ItemCount=500] 29.96 µs 28.98 µs -3.3% 0 B 0 B
2 ComputeDiff_KeyedList_SameOrder [ItemCount=500] 29.13 µs 29.67 µs +1.9% 0 B 0 B
2 ComputeDiff_KeyedList_Reordered [ItemCount=500] 29.74 µs 28.58 µs -3.9% 0 B 0 B
3 ComputeDiff_KeyedList_SameOrder [ItemCount=500] 30.10 µs 29.44 µs -2.2% 0 B 0 B
3 ComputeDiff_KeyedList_Reordered [ItemCount=500] 30.23 µs 32.77 µs +8.4% 0 B 0 B

Result: within noise. SameOrder measured −5.8%, +1.9% and −2.2%, and Reordered measured −3.3%, −3.9% and +8.4%. Neither version allocates. In this 3-round A/B I can't separate the remaining change from noise.

Setup: BenchmarkDotNet v0.13.0 --config perflab (InProcess, MemoryDiagnoser, 3 warmup + 15 measured iterations); AMD EPYC 9V74, 2 vCPU, Ubuntu 24.04 container; .NET SDK 12.0.100-alpha.1.26521.103, .NET 12.0.0 runtime (X64 RyuJIT). main is the PR's merge base 4f556f73a6. PR is the same tree with only this PR's src/**/src changes applied. Both builds use the same benchmark source. Run order: main, PR, main, PR, main, PR.

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

BuildKeyToInfoLookup performed two hash lookups per keyed item for both
the old tree (ContainsKey + indexer set) and the new tree (TryGetValue +
indexer set). Use TryAdd and CollectionsMarshal.GetValueRefOrAddDefault
so each key is hashed once per tree.

Adds KeyedListDiffBenchmark to the Components perf project.

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

The required frozen head/base source and existing-feedback bundle was not supplied, preventing independent provenance and prior-feedback deduplication checks.

No open issues 🎉

What changed in this PR

This PR reduces dictionary lookups when Blazor builds the keyed-item lookup during render-tree diffing, while preserving duplicate-key detection.

Changes:

  • Uses TryAdd for old-tree keys and CollectionsMarshal.GetValueRefOrAddDefault for new-tree keys.
  • Adds benchmarks for 500-item keyed lists in unchanged order and with reordering, insertion, and removal.
File Description
src/​Components/​Components/​src/​RenderTree/​RenderTreeDiffBuilder.cs Removes redundant dictionary lookups when processing keyed siblings.
src/​Components/​Components/​perf/​KeyedListDiffBenchmark.cs Adds same-order and reordered keyed-list diff benchmarks.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

The only CI failure is Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices in the MVC functional tests. This PR changes only RenderTreeDiffBuilder in Components, so the failure is unrelated. The test has a history of flakiness (quarantine issue #67340). I'm rerunning aspnetcore-ci.

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

davidfowl commented Oct 30, 2026 •

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

🤖 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-ci

Rerun reason: the failures don't touch the code changed here (RenderTreeDiffBuilder keyed lookups), and the same commit passed both tests in the previous run.

  • BlazorTemplates.Tests.BlazorWebTemplateTest.BlazorWebTemplate_ConditionalPasskeyRegistration: browser/passkey template test, 6.72% historical failure rate per Build Analysis.
  • Kestrel Http2ConnectionTests.ConnectionResetLoggedWithActiveStreams: Kestrel in-memory test, unrelated to Components.

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

Copy link
Copy Markdown
Member Author

Compliance check: this is an internal-only change to RenderTreeDiffBuilder.BuildKeyToInfoLookup, with no public API changes. Duplicate-key detection and the exception message are unchanged (the existing duplicate-key tests pass). The produced diffs are identical.

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

Keep only the single-lookup TryAdd for the old-tree pass; the new-tree pass
returns to TryGetValue + indexer to comply with the no-CollectionsMarshal rule.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

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

Copy link
Copy Markdown
Member Author

Small difference between

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