Skip to content

perf(vsm): Stop materialising empty state-trigger collections - #24235

Merged
MartinZikmund merged 2 commits into
masterfrom
dev/mazi/perf-visualstate-triggers
Oct 10, 2026
Merged

MartinZikmund merged 2 commits into
masterfrom
dev/mazi/perf-visualstate-triggers

Conversation

@MartinZikmund

Copy link
Copy Markdown
Member

GitHub Issue: closes #24226

PR Type:

🔄 Refactoring (no functional changes, no api changes)

What changed? 🚀

VisualState.StateTriggers is a lazily-materialising getter: with no list on the DP it creates a DependencyObjectCollection, subscribes to its VectorChanged and writes it back through SetValue. That is right for a caller intending to add a trigger, but all four consumers in VisualStateGroup only read — ExecuteOnTriggers (three call sites), HasStateTriggers, and GetActiveTrigger twice. So every visual state of every templated control materialised a collection, a subscription, a DependencyPropertyDetails entry and a pooled-array rent to represent no triggers at all, which is what almost every state has.

Add StateTriggersOrDefault, which reads the DP without materialising, and use it at the four read sites. Behaviour is identical: with no collection there are no triggers, so each loop body ran zero times anyway and HasStateTriggers returned false. A caller that actually adds a trigger still goes through StateTriggers and creates it lazily as before.

Measured impact 📊

Workload Metric Before After Δ
list.scroll-step alloc / step 133,277 B 121,814 B −8.6 %
list.scroll-step time / step 1.6278 ms 1.5791 ms −3.0 %
control layout.full-pass alloc 4,096,259 B 4,096,127 B ±0
control grid.full-pass alloc 51,833 B 51,833 B ±0
control tree.build alloc 21,946,936 B 21,942,484 B ±0

Same 2,000-item virtualised ListView workload, 3 runs of the full set in identical order, median. Measured on a tree that already has the resource-scope enumerator fix applied.

Validation ✅

Runtime tests, Skia Desktop — Given_VisualStateManager, Given_EventTrigger, Given_Button, Given_CheckBox, Given_RadioButton, Given_ToggleSwitch, Given_HyperlinkButton, Given_AppBarButton, Given_Style, Given_ListViewBase: 221 run, 214 passed, 11 skipped, 7 failed. Every visual-state and control test passes; the only failures are the Given_ListViewBase set already established as pre-existing against baseline builds in the other PRs of this series.

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!)

Copilot AI lite review requested due to automatic review settings August 27, 2026 07:19
@github-actions

github-actions Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

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.

Pull request overview

This PR addresses a performance issue in Uno’s VisualStateManager trigger evaluation by avoiding the lazy materialization of an empty StateTriggers collection when call sites only need to read triggers.

Changes:

  • Added a non-materializing accessor (StateTriggersOrDefault) on VisualState to read the DP value without creating an empty collection.
  • Updated VisualStateGroup trigger-reading paths (ExecuteOnTriggers, HasStateTriggers, GetActiveTrigger) to use the new accessor to avoid unnecessary allocations.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/Uno.UI/UI/Xaml/VisualStateGroup.cs Switched trigger iteration/read logic to use StateTriggersOrDefault to avoid materializing empty collections.
src/Uno.UI/UI/Xaml/VisualState.cs Introduced StateTriggersOrDefault to read StateTriggersProperty without forcing lazy collection creation.

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

Comment thread src/Uno.UI/UI/Xaml/VisualState.cs Resolved
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 230533 found UI Test snapshots differences: skia-linux-screenshots: 73, skia-windows-screenshots: 218

Details
  • skia-linux-screenshots: 73 changed over 2366

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • DropDownButtonPage.png-dark
    • Attributed_text_FontSize_Changing.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • ImageIconPage.png-dark
    • ImageIconPage.png
    • ContentControl_Inheritance.png
    • CalendarView_Theming.png-dark
    • Buttons.png
    • DisplayInformation.png-dark
    • DisplayInformation.png
    • ExpanderColorValidationPage.png-dark
    • ElementLevelTheme.png-dark
    • ExpanderColorValidationPage.png
    • ElementLevelTheme.png
    • ContextRequested.png-dark
    • DynamicFont.png
    • Examples.png
    • Focus_FocusVisual_Properties.png-dark
    • Gamepad_CurrentReading.png-dark
  • skia-windows-screenshots: 218 changed over 2368

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Attributed_text_FontSize_Changing.png-dark
    • BitmapImage_vs_SvgImageSource.png
    • Attributed_text_FontSize_Changing.png
    • ButtonClippingTestsControl.png-dark
    • Basics Pivot Test.png-dark
    • ButtonClippingTestsControl.png
    • Clipping652.png-dark
    • Clipping652.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ChatBox.png-dark
    • ClipboardTests.png-dark
    • ChatBox.png
    • Buttons.png-dark
    • Buttons.png
    • Dopes.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • Contacts_Pick.png-dark
    • Contacts_Pick.png

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/perf-visualstate-triggers branch from 398a80a to 9a060b8 Compare August 29, 2026 10:12
@unodevops

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 231013 found UI Test snapshots differences: skia-linux-screenshots: 73, skia-windows-screenshots: 228

Details
  • skia-linux-screenshots: 73 changed over 2366

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • CalendarView_Theming.png-dark
    • ContentControl_Inheritance.png
    • Examples.png
    • Buttons.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • ClipboardTests.png-dark
    • ClipboardTests.png
    • ContextRequested.png-dark
    • ExpanderColorValidationPage.png-dark
    • DynamicFont.png
    • ExpanderColorValidationPage.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • ImageBrushInList.png-dark
    • ImageBrushInList.png
    • ImageIconPage.png-dark
    • ImageIconPage.png
    • Image_Margin_Large.png
  • skia-windows-screenshots: 228 changed over 2368

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Basics Pivot Test.png
    • BitmapImage_vs_SvgImageSource.png-dark
    • BitmapImage_vs_SvgImageSource.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ContentControl_SelectorInheritance.png-dark
    • Hyperlink_Button.png-dark
    • Hyperlink_Button.png
    • Hyperlink_CanExecute_False.png-dark
    • Hyperlink_CanExecute_False.png
    • Hyperlink_Disabled.png-dark
    • Hyperlink_Disabled.png
    • EmailManagerTests.png-dark
    • EmailManagerTests.png
    • ExpanderColorValidationPage.png-dark
    • ImagesInlineInFlipView.png-dark
    • ImagesInlineInFlipView.png
    • ImageSourceUrlMsAppDataScheme.png-dark
    • ImageSourceUrlMsAppDataScheme.png
    • ChatBox.png-dark

@MartinZikmund
MartinZikmund changed the base branch from feature/breakingchanges to master September 2, 2026 20:01
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 231673 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
    • Focus_FocusVisual_Properties.png-dark
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ClipboardTests.png-dark
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
    • ImageIconPage.png-dark
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • DisplayInformation.png-dark
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
  • skia-windows-screenshots: 2310 changed over 2402

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AndroidWindowInsets.png
    • AppBarButtonTest.png
    • Accessibility_ScreenReader.png-dark
    • ApplicationViewMode.png
    • AppWindowClosing.png-dark
    • Arrange_Performance01.png
    • AppWindowPresenters.png-dark
    • AppWindowPositionAndSize.png
    • AutoBorderStretchwithleftmargin.png-dark
    • AutomationPropertiesExtensions_Role.png
    • AutoBorderStretchwithleftmargin.png
    • AutoSizedPathCentered.png
    • AutoSuggestBox_Description.png
    • AutoSizedTopLeft.png
    • AutoSuggestBox_SoftKeboard.png
    • BasicAcrylicBrushTest2.png
    • BackGesture.png-dark
    • Battery.png
    • Border_CornerRadius_Clipping2.png
    • Basics Pivot Test.png-dark
  • wasm: 11 changed over 1076

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

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

Code review assessment: reading the nullable existing trigger collection is aligned with WinUI's standard VSM path, which returns when m_pStateTriggerCollection is null rather than creating an empty collection: https://github.com/microsoft/microsoft-ui-xaml/blob/439bda90582f7892ca595a193f55dbfc6ae2010c/dxaml/xcp/components/vsm/StandardVisualStateManagerDataSource.cpp#L388-L400 . The normal StateTriggers getter still creates/subscribes the collection when needed. No blocking behavior issue found. The nullable return annotation can be clarified without replacing it with a materialized DP value.

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/perf-visualstate-triggers branch from 9a060b8 to 8397ceb Compare October 3, 2026 08:41
Copilot AI lite review requested due to automatic review settings October 3, 2026 08:41
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 1m 43s —— View job


Review complete

  • Gather context (diff, changed files)
  • Review VisualState.cs changes
  • Review VisualStateGroup.cs changes
  • Check AGENTS.md rule compliance
  • Post inline findings
  • Post summary

Verdict: fix-first. The approach is sound (non-materialising read accessor, read sites switched via pattern matching, no public API/behavior change), but the refactor missed one read site, which undercuts the stated completeness of the fix.

Findings posted inline: 2

  • 🟠 Correctness/completeness (unresolved as inline — outside diff context): VisualStateGroup.cs:530, inside RefreshStateTriggers, still reads oldState is { StateTriggers: { Count: > 0 } } through the materialising getter instead of StateTriggersOrDefault. HasStateTriggers() only guarantees some state in the group has triggers, not that oldState (CurrentState) does — so a no-trigger current state still gets an empty DependencyObjectCollection materialised, subscribed, and written back via SetValue on every RefreshStateTriggers() call. This is the same allocation pattern the PR removes everywhere else, just missed at a fifth read-only call site (PR description says "four consumers"). GitHub wouldn't let me anchor a comment on this unchanged line since it falls outside the diff hunk, so flagging it here: suggested fix is oldState?.StateTriggersOrDefault is { Count: > 0 }.
  • 🟡 Minor contract clarity: VisualState.cs:132 — StateTriggersOrDefault is typed non-nullable (IList<StateTriggerBase>) but returns null whenever unset, which is the common/intended case. Not a compiler issue today (file is nullable-oblivious) but misleading for an internal member that may gain callers; the bot review already flagged this too.

Other checks: no new DependencyProperty, no async/cancellation surface touched, no events declared, no XAML changes, code style (tabs/Allman/comment length) and the doc comment on the new member are consistent with .claude/rules/code-style.md. Conventional Commit title format is correct. No new tests were added, which is reasonable for a behavior-preserving internal refactor backed by the existing runtime-test suite cited in the PR description — but note that suite wouldn't have caught the missed call site above since it's an allocation-only regression, not a behavioral one.

Comment thread src/Uno.UI/UI/Xaml/VisualState.cs Resolved

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.

Copilot review overview

🟡 Changes recommended

RefreshStateTriggers still contains a materializing trigger read that should use StateTriggersOrDefault.

Review effort: Lite
Findings: 2 Medium severity

Open (2)

Comment thread src/Uno.UI/UI/Xaml/VisualStateGroup.cs Resolved
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 237145 found UI Test snapshots differences: skia-linux-screenshots: 119, skia-windows-screenshots: 186

Details
  • skia-linux-screenshots: 119 changed over 2454

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CalendarView_Theming.png-dark
    • DisplayInformation.png-dark
    • Buttons.png-dark
    • Buttons.png
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • ExpanderColorValidationPage.png-dark
    • DynamicFont.png-dark
    • ExpanderColorValidationPage.png
    • DynamicFont.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_Enumeration.png-dark
    • ImageIconPage.png-dark
    • ImageIconPage.png
    • KeyboardNavigationSample.png-dark
    • KeyboardNavigationSample.png
  • skia-windows-screenshots: 186 changed over 2456

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • CalendarView_Theming.png-dark
    • DisplayInformation.png-dark
    • ClipboardTests.png-dark
    • ClipboardTests.png
    • Examples.png
    • Focus_FocusVisual_Properties.png-dark
    • Grid_Spacing_Adjustable.png-dark
    • Grid_Spacing_Adjustable.png
    • Grid_Star_Auto_WithTextblock.png-dark
    • Grid_Star_Auto_WithTextblock.png
    • Grid_Style_Local_Override.png-dark
    • Grid_Style_Local_Override.png
    • Grid_Two_bottom_row_Auto__middle_col_auto.png-dark
    • Grid_Two_bottom_row_Auto__middle_col_auto.png
    • Grid_with_attributed_string.png-dark
    • Grid_with_Text_VerticalAlignment_With_Margin.png-dark
    • Grid_with_attributed_string.png

MartinZikmund and others added 2 commits October 9, 2026 15:52
VisualState.StateTriggers is a lazily-materialising getter: with no list
on the DP it creates a DependencyObjectCollection, subscribes to its
VectorChanged and writes it back through SetValue. That is right for a
caller intending to add a trigger, but all four consumers in
VisualStateGroup only read -- ExecuteOnTriggers (three call sites),
HasStateTriggers, and GetActiveTrigger twice. So every visual state of
every templated control materialised a collection, a subscription, a
DependencyPropertyDetails entry and a pooled-array rent to represent no
triggers at all, which is what almost every state has.

Add StateTriggersOrDefault, which reads the DP without materialising, and
use it at the four read sites. Behaviour is identical: with no collection
there are no triggers, so each loop body ran zero times anyway and
HasStateTriggers returned false. A caller that actually adds a trigger
still goes through StateTriggers and creates it lazily as before.

Measured (specs/059-performance-improvements): a virtualised ListView
scroll step drops from 133,277 B to 121,814 B (-8.6%) and from 1.6278 ms
to 1.5791 ms (-3.0%), with the layout, grid and tree-build control
workloads flat. Cumulatively with the two preceding fixes, a scroll step
is down 21% on allocations. 221 visual-state and control runtime tests:
every one passes except the ListViewBase set already established as
pre-existing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015DSdL5YzLhjx8CeGXZf1Au
Copilot AI lite review requested due to automatic review settings October 9, 2026 13:58
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/perf-visualstate-triggers branch from 8397ceb to 21b01af Compare October 9, 2026 13:58

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 14s —— View job


Review summary

Verdict: ship.

I re-reviewed the PR at 21b01af1. It addresses both open findings from the earlier review.

  • Missed read site: RefreshStateTriggers (VisualStateGroup.cs:532) now reads oldState?.StateTriggersOrDefault is { Count: > 0 }. No read-only consumer in VisualStateGroup.cs calls the materialising StateTriggers getter any more.
  • Nullability contract: StateTriggersOrDefault is now IList<StateTriggerBase>?, with #nullable enable / #nullable restore scoped to that member. This matches the pattern-matching callers.

Counts: 0 blocking, 0 new findings.

Cross-cutting notes

  • The change doesn't alter behavior. A state with no trigger collection has no triggers, so the loops that now skip it ran zero times before. Adding a trigger still goes through the lazy StateTriggers getter.
  • I didn't add tests. The change affects allocations only, so the existing runtime tests can't catch a regression. The numbers in the PR description are the evidence for it.
  • I didn't build or run anything. This is a review by inspection.
  • The screenshot-comparison diffs in the CI comments span hundreds of unrelated samples, including the 2310 on Windows. That looks like a baseline or infrastructure issue rather than something this change causes. Confirm it against a master run before merging.

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 238554 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 1150

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Examples.png
    • DisplayInformation.png-dark
    • Focus_FocusVisual_Properties.png-dark
    • Focus_FocusVisual_Properties.png
    • DropDownButtonPage.png-dark
    • ImageBrushAlignmentXY.png-dark
    • ImageBrushAlignmentXY.png
  • skia-windows-screenshots: 1150 changed over 2474

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarButtonWithIconTest.png
    • AutoBorderStretchwithleftmargin.png
    • BackGesture.png-dark
    • BackGesture.png
    • BitmapIcon_Monochromatic.png-dark
    • BitmapIcon_Monochromatic.png
    • BorderCenteredwithmargins.png-dark
    • BorderCenteredwithmargins.png
    • BorderLeftwithmargins.png-dark
    • BorderLeftwithmargins.png
    • BorderVersusPanelClipping.png-dark
    • BorderVersusPanelClipping.png
    • Brushes_ImplicitConvert.png-dark
    • Brushes_ImplicitConvert.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Capture with overlap.png-dark
    • Capture with overlap.png
    • ClippingToControlBounds.png-dark
    • ClippingToControlBounds.png

@mergify

mergify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@MartinZikmund
MartinZikmund merged commit c00a6ae into master Oct 10, 2026
51 checks passed
@MartinZikmund
MartinZikmund deleted the dev/mazi/perf-visualstate-triggers branch October 10, 2026 07:15
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.

Every VisualState materialises an empty trigger collection when read

5 participants