Skip to content

perf(uno-ui): Index DO collections in tree walks - #24519

Merged
MartinZikmund merged 1 commit into
masterfrom
dev/mazi/perf-docollection-walk
Sep 16, 2026
Merged

MartinZikmund merged 1 commit into
masterfrom
dev/mazi/perf-docollection-walk

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #24517

PR Type:

🔄 Refactoring (no functional changes, no api changes)

What changed? 🚀

The Enter, Leave and resource-binding walks visited the collections a property holds through IEnumerable, so each visit boxed a List<T>.Enumerator (40 B). Every VisualStateGroup, VisualState, Setter, StateTrigger and VisualTransition collection of every templated control paid it on each Enter, each Leave and each theme update — in a virtualized list, on every recycled container. VisualStateManager.VisualStateGroups, which XAML codegen stores as a VisualStateGroup[], boxed an array enumerator on the same walks, and TextBlock.UpdateThemeBindings boxed one per InlineCollection.

DependencyObjectCollectionBase now carries the backing list as an indexable IList, and the six walk sites enumerate through one DependencyObjectItems ref struct that indexes framework DO collections and arrays, and falls back to the value's own enumerator for anything else. TextBlock uses the struct enumerator InlineCollection already had.

Two details worth calling out:

  • Mutation during a walk keeps throwing. Indexing alone would silently skip or revisit an item if a callback modified the collection mid-walk, where the old enumerator threw. The collection now bumps a version on each mutation and the walker checks it, so the behaviour is the same as List<T>.Enumerator — including the Enter/Leave catch that swallows it, and the theming walk where it propagates. WinUI instead Lock()s the collection during the walk (CDOCollection::EnterImpl); adopting that would change which code throws, so it belongs in its own change.
  • Not a full parity port. In WinUI the collection's own EnterImpl/LeaveImpl walks its items; in Uno the owner still drives the walk (the existing TODO Uno in DependencyObject.PropertySystem.mux.cs). This change only removes the boxing from the owner-driven walk; the seam it adds is the data source a future port would reuse.

Measured impact 📊

Managed bytes allocated per iteration on the UI thread (GC.GetAllocatedBytesForCurrentThread, median of 7 rounds, two runs per side; reproduces within ~1 %):

Workload Before After Δ
Enter + Leave Button 18,592 B 17,376 B −6.5 %
Enter + Leave CheckBox 24,744 B 21,848 B −11.7 %
Enter + Leave ToggleSwitch 48,215 B 44,576 B −7.5 %
Enter + Leave ListViewItem 37,768 B 32,872 B −13.0 %
Enter + Leave TextBox 30,416 B 27,024 B −11.2 %
Enter + Leave a 40-control page 796,817 B 721,057 B −9.5 %
Theme toggle on that page 539,832 B 514,872 B −4.6 %
ListView (2,000 items) scroll step 177,950 B 161,173 B −9.4 %

Every saving is an exact multiple of 40 B, i.e. exactly the enumerator boxes and nothing else.

Measured with a headless Skia app (Uno.UI.Runtime.Skia.Headless) that project-references the framework, with Fluent resources merged. Wall-clock is deliberately not reported: it varied by 2× between identical runs on this machine, far above any effect. Gen0 counts were captured too, but at 0–2 per round they are too coarse to show a difference.

Overlap with #24235. On the scroll workload that PR alone gives −6.4 %, this one alone −9.4 %, and both together −9.4 % — measured on a tree with #24235 cherry-picked. They remove the same enumerators from opposite ends, so the wins are not additive and this PR subsumes it on that workload.

Validation ✅

Runtime tests, Skia Desktop — Given_VisualStateManager, Given_ThemeResource, Given_ElementTheme, Given_ElementTheme_Resolution_Regression, Given_MergedAppResources_ThemeResource, Given_Theme_Materialization, Given_FrameworkElement_ThemeResources, Given_DependencyObjectCollection, Given_Style, Given_ResourceDictionary, Given_Storyboard, Given_TextBlock, Given_Run, Given_Hyperlink, Given_Button, Given_CheckBox, Given_CheckBox_ThemeResource_Regression, Given_ToggleSwitch, Given_ListViewBase: 506 run, 498 passed, 15 skipped, 1 inconclusive, 7 failed.

The failures are the Given_ListViewBase layout-rounding/timeout set plus Given_TextBlock.When_Inlines_Transitively_Change, all of which fail identically on a build of the merge-base without this change (verified by rebuilding and rerunning just those tests).

Two runtime tests were added to Given_DependencyObjectCollection, covering theme-bound values that live inside collections the walks visit (GradientStops on a brush, a Run in TextBlock.Inlines): one for a subtree that leaves and re-enters the tree under the other theme, one for a subtree that joins the tree with a theme already set.

Both were checked against a deliberately broken walker (indexed path visiting no items): When_Subtree_Reenters_Tree_Then_Items_In_Collections_Are_Updated fails under it, so it genuinely guards this change; When_Themed_Subtree_Enters_Tree_Then_Items_In_Collections_Are_Resolved still passes, so it covers Enter-time theme resolution through another path rather than this walk. Both pass on a build of the merge-base, i.e. they assert behaviour this PR preserves rather than introduces.

PR Checklist ✅

  • 🧪 Added Runtime tests, UI tests, or a manual test sample (for bug fixes / features, if applicable)
  • 📚 Docs have been added/updated following the documentation template (for bug fixes / features) — n/a, no API or behaviour change for app authors
  • 🖼️ Validated PR Screenshots Compare Test Run results. — to check once CI has run
  • ❗ Contains NO breaking changes
  • 👀 Reviewed 2 other open pull requests (optional but appreciated!)

🤖 Generated with Claude Code

https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX


Internal tracking: unoplatform/uno-private#2349 (finding 7), under unoplatform/uno-private#2346.

The Enter, Leave and resource-binding walks visited the collections a property
holds through IEnumerable, boxing a List<T>.Enumerator per collection per visit.
Every VisualStateGroup, VisualState, Setter, StateTrigger and VisualTransition
collection of a templated control paid it on each Enter, Leave and theme update,
as did the VisualStateGroup[] emitted by XAML codegen, Storyboard children and
TextBlock inlines.

DependencyObjectCollectionBase now exposes its backing list as an indexable
IList, and the walks enumerate through DependencyObjectItems, which indexes
framework DO collections and arrays and falls back to the value's own enumerator
for anything else.

The collection bumps a version on each mutation and the walker checks it, so a
collection modified mid-walk still throws as List<T>.Enumerator did. WinUI
instead locks the collection for the duration of the walk
(CDOCollection::EnterImpl); that changes which caller throws, so it is left for
its own change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX
Copilot AI lite review requested due to automatic review settings September 16, 2026 08:03
@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 3m 17s —— View job


Review complete ✅

Todo list:

  • Gather context (PR description, diff, changed files)
  • Review DependencyObjectCollection.cs (new indexable backing + versioning)
  • Review DependencyObject.PropertySystem.mux.cs walk-site changes
  • Review DependencyObject.Theming.cs walk-site changes
  • Review TextBlock.cs / InlineCollection.cs changes
  • Review new runtime tests in Given_DependencyObjectCollection.cs
  • Post inline findings
  • Post summary

Verdict: ship (1 nit)

Findings by severity: 0 blocking, 0 major, 1 minor (posted inline).

What I checked

  • Correctness of the versioned-indexing approach: DependencyObjectCollectionBase.IndexedItems/ItemsVersion are only ever set/mutated from DependencyObjectCollection<T> (the sole subclass), so DependencyObjectItems never sees a non-null IndexedItems with a stale _items reference. Every list-mutating member (this[] setter, Insert, RemoveAt, Add, Clear, and Remove via RemoveAt) bumps the version, so the "throw on mutation during enumeration" contract genuinely matches List<T>.Enumerator rather than being a partial guard.
  • Boxing elimination is real: since T : DependencyObject (reference type), indexing through IList never boxes, and VisualStateGroup[] matches the object[] array-covariance branch (reference-type element arrays are covariant), so that path is exercised too, matching the PR's stated allocation wins.
  • Cast safety at the (DependencyObject)innerValue sites (DependencyObject.PropertySystem.mux.cs, DependencyObject.Theming.cs): confirmed IAdditionalChildrenProvider.GetAdditionalChildObjects() is declared/implemented as IEnumerable<DependencyObject> (only implementer is Storyboard), so the cast can't fail at runtime.
  • Behavior parity: verified against the pre-change code that the Enter/Leave walk's try/catch and the theming walk's uncaught propagation are unchanged in scope — the version-check exception surfaces exactly where the PR description says it does, nothing newly swallowed or newly thrown.
  • Fallback path: non-DependencyObjectCollectionBase, non-array IEnumerable values (e.g. a plain ObservableCollection<T>) still fall back to boxing their own enumerator — correctly scoped, no behavior change for those.
  • Style, nullable annotations, comment discipline, and event/DP conventions in the touched files are consistent with AGENTS.md/.claude/rules/code-style.md.

Cross-cutting notes

  • The one inline finding is a stale <see cref="When_Theme_Changes_Then_Items_In_Collections_Are_Updated"/> in a test doc comment — the method was renamed to When_Subtree_Reenters_Tree_Then_Items_In_Collections_Are_Updated but the cross-reference in the sibling test's remarks wasn't updated. Cosmetic only (doesn't affect the assertions), included a suggested fix.
  • The PR is explicit and correctly scoped about what it is not doing (WinUI's Lock()-during-walk semantics, full EnterImpl/LeaveImpl ownership move) rather than silently changing throw behavior — appreciated, and consistent with the repo's root-cause-first / no-scope-creep guidance.
  • Validation label: this was a code review by inspection (diff read end-to-end, cross-checked call sites and interface contracts) — I did not build or run the runtime tests myself in this session.

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.

🟡 Changes recommended

Mutation coverage and two test documentation/annotation nits remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

This PR reduces enumerator allocations during Uno UI tree and theme walks while preserving mutation detection behavior.

Changes:

  • Adds indexed traversal for dependency-object collections and arrays.
  • Optimizes Enter/Leave, theming, and TextBlock inline walks.
  • Adds regression tests for themed collection items.
File summaries
File Reviewed changes and findings
src/Uno.UI/UI/Xaml/Documents/InlineCollection.cs Exposes allocation-free inline enumeration. No additional findings.
src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs Adds indexed traversal and mutation tracking. Moderate finding (1 vote): add mutation-during-walk regression coverage.
src/Uno.UI/UI/Xaml/DependencyObject.Theming.cs Uses indexed theme-resource traversal. No additional findings.
src/Uno.UI/UI/Xaml/DependencyObject.PropertySystem.mux.cs Uses indexed Enter/Leave walks. No additional findings.
src/Uno.UI/UI/Xaml/Controls/TextBlock/TextBlock.cs Uses the allocation-free inline enumerator. No additional findings.
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs Adds themed collection tests. Nits (3 votes each): fix the dangling cref and add GitHubWorkItem annotations to the issue-specific tests.
Review details

Suppressed comments (2)

src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs:101

  • This second regression test also guards issue #24517, but it is not linked with GitHubWorkItem, unlike issue-specific runtime tests elsewhere. Add the same issue annotation here so the test remains traceable when it fails.
	[TestMethod]

src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs:33

  • The new ItemsVersion path is the only thing preserving the old fail-fast behavior after replacing List<T>.Enumerator with indexing, but the added tests never mutate a walked DependencyObjectCollection. Add regression coverage that changes the collection from a walk callback and verifies Enter/Leave handle the resulting InvalidOperationException as before while the theme walk still propagates it; otherwise a future mutation path can omit this bump and silently alter traversal.
		private protected void OnItemsMutated() => ItemsVersion++;
  • Files reviewed: 6/6 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 233976 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2310, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ClipboardTests.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
    • DisplayInformation.png-dark
  • skia-windows-screenshots: 2310 changed over 2408

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AndroidWindowInsets.png-dark
    • AppBarToggleButtonTest.png-dark
    • ApplicationViewSpanningRectsPage.png-dark
    • AppWindowPositionAndSize.png
    • ArcSegment.png-dark
    • Attributed_text_Supserscript.png
    • AutoBorderStretchwithrightmargin.png
    • AutomationProperties_Name.png
    • AutoSuggestBox_Description.png
    • AutoSuggestBox_Icons.png-dark
    • BasicAutoSuggestBox.png-dark
    • BasicAutoSuggestBox.png
    • Battery.png-dark
    • Battery.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • BitmapIcon_Monochromatic.png-dark
    • BitmapIcon_Monochromatic.png
    • BorderBottomwithmargins.png-dark
    • BorderBottomwithmargins.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • UITests.Uno_Web.Http.CookieManagerTests
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the exact current head. Indexed DependencyObject collection access preserves traversal order and collection semantics while removing repeated enumeration overhead. No significant issue found.

@mergify

mergify Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enter, Leave and theme walks box an enumerator per DependencyObject collection

5 participants