Repository navigation
perf(theming): Walk resource dictionaries without an iterator - #24523
Conversation
|
Claude finished @MartinZikmund's task in 3m 3s —— View job Review complete ✅Todo list
Verdict: ShipNo inline comments were posted — I traced
No SOLID/async/cross-platform/DependencyProperty/event-type/XAML/commit-format issues — this is internal, non-UI-suffixed shared code touched uniformly across all targets, and the commit type ( Note on validation method: this was a code-level review (manual trace + diff read), not a rebuild/rerun — I relied on the author's extensive runtime-test evidence in the PR description rather than re-executing the suite myself. |
There was a problem hiding this comment.
🔵 Needs a closer look
Address the requested test metadata, platform-condition, and Android coverage updates.
Pull request overview
This PR reduces theming/resource lookup allocations with a shared struct-based resource dictionary walker while preserving lookup order.
Changes:
- Adds allocation-free resource dictionary enumeration.
- Updates theme, implicit-style, and visual-tree lookups.
- Adds nearest-scope precedence regression coverage.
File summaries
| File | Summary |
|---|---|
src/Uno.UI/UI/Xaml/ResourceResolver.cs |
Uses the allocation-free walker for visual-tree retrieval. |
src/Uno.UI/UI/Xaml/DependencyObject.Theming.cs |
Uses the walker during theme reference resolution. |
src/Uno.UI/UI/Xaml/DependencyObject.Store.cs |
Implements the shared resource dictionary walker. |
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_Style.cs |
Adds implicit-style scope-order regression coverage. |
Review details
Suppressed comments (3)
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_Style.cs:99
- This new regression test is skipped on Android, so the nearest-scope ordering introduced by the shared
ResourceDictionaryWalkerhas no coverage on that target even though the change is intended for all platforms. Please add an Android-compatible test for the same precedence (or remove the skip); reusing the existingContentControlskip leaves this new behavior unverified there.
[Ignore("ContentControl implicit styles don't pass in CI on Android, as for When_ImplicitStyle")]
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_Style.cs:97
- This new regression test directly covers issue #24522, but it has no
GitHubWorkItemmetadata. Please annotate it so the test remains traceable to the issue it protects, as required for issue-covering runtime tests.
[TestMethod]
[RunsOnUIThread]
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_Style.cs:100
- Please use a
PlatformConditionattribute instead of a compile-time#ifaround this platform skip. Runtime-test conventions keep platform selection in attributes so discovery and filtering remain consistent across targets; excludeRuntimeTestPlatforms.Androiddirectly.
#if __ANDROID__
[Ignore("ContentControl implicit styles don't pass in CI on Android, as for When_ImplicitStyle")]
#endif
- Files reviewed: 4/4 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-24523/wasm-skia-net9/index.html |
|
The build 233998 found UI Test snapshots differences: Details
|
|
|
|
Claude finished @MartinZikmund's task in 3m 9s —— View job Review complete ✅Todo list
Verdict: Ship, pending CI screenshot confirmationInline findings: 0. I re-traced
The walker itself is a faithful, allocation-free translation of the original iterator: Cross-cutting concern (not an inline finding)CI build 233998 failed, and the screenshot-diff comment reports 2,310 of 2,408 |
|
Addressed the review feedback in Copilot review items1. Missing 2. Changing a platform gate can silently stop a test running rather than skip it visibly, so I checked that specifically rather than trusting a green count: on Skia Desktop the class reports 4/4 with 3. No Android coverage for the nearest-scope ordering — not addressed in code, deliberately. The skip mirrors the pre-existing one on Screenshot differencesThe
Identical on four independent PRs including one already merged, so it is a baseline artifact on the Windows leg rather than anything a PR did. The asymmetry points the same way: a resource-ordering regression would move both Skia legs alike, not 2310 of 2408 on Windows while Linux moves 57 of 2348. Android runtime shardCovered in the inline thread, but noting it here since it is the one open item: the ADO timeline shows |
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-24523/wasm-skia-net9/index.html |
|
The build 234206 found UI Test snapshots differences: Details
|
|
|
089481f to
d49c585
Compare
|
Claude finished @MartinZikmund's task in 2m 32s —— View job Review complete ✅Todo list
Verdict: Fix-first — one unresolved P1 blocks mergeNo new inline comments. I re-traced
Everything else checks out: the walker is a faithful, allocation-free translation of the removed iterator (containing dictionary → deferred Screenshot diffs: the |
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-24523/wasm-skia-net9/index.html |
|
The build 234481 found UI Test snapshots differences: Details
|
|
|
d49c585 to
002cf9c
Compare
|
Claude finished @MartinZikmund's task in 1m 9s —— View job Review complete ✅Todo list
Verdict: No new findings — the outstanding P1 from the prior round is still the blockerThis trigger fired on a branch update, but No new inline comments posted. Status of the two open threads, unchanged from the last review round:
Everything else continues to check out: |
|
The build 237161 found UI Test snapshots differences: Details
|
There was a problem hiding this comment.
Re-review at head 002cf9c (rebased onto master 3bcf00c). Code review only; nothing was built or run here.
What changed since 089481f: the three new commits repeat the earlier commits (same messages and changed lines). The rebase applied cleanly, and the test moved to src/Uno.UI.RuntimeTests/Microsoft/UI/Xaml/Given_Style.cs.
Blocking:
- Given_Style.cs:97 uses RuntimeTestPlatforms.NativeAndroid, which does not exist on master (the enum has NativeWinUI and the Skia values). This should fail with CS0117 and break Uno.UI.RuntimeTests, consistent with the failing Skia Runtime Tests build check on this head. Please confirm against the build log.
- The Android walker regression is still open. The IDisposable change was in 089481f, where the Android shard timeouts still reproduced, and nothing in this head changes the walker. Please post Android shard results for 002cf9c showing the timeouts are gone.
- The Android skip on the new test removes the only Android coverage of nearest-scope ordering. The comment "as for When_ImplicitStyle above" is stale, since master no longer skips that test on Android. Drop the skip, or verify on Android and update the comment. The GitHubWorkItem links to #24522 (the performance issue), not the CI failure. Please link the Skia Desktop run the commit message refers to.
Non-blocking:
- The walker keeps the removed iterator's visit order.
- WinUI's implicit-style lookup also goes nearest-first and ends with app resources. WinUI also stops at the templated parent for non-controls; Uno's walker does not. That divergence predates this PR.
- The retention mechanism behind the Dispose change has not been shown with a profile.
GetResourceDictionaries is a C# iterator, so every call allocates a state machine before producing a dictionary — including the common case where no ancestor carries resources and the walk yields nothing. It runs once per theme reference (an object with N refs performs N separate ancestor walks), twice per element Enter for the implicit-style lookup, and on every visual-tree resource retrieval. Add EnumerateResourceDictionaries, a struct enumerator that performs that walk without allocating, and use it from those three lookups. The iterator stays for the two callers that materialise an array, but now delegates to the walker, so the visit order — containing dictionary, each ancestor's non-empty Resources, then the application resources — lives in one place. The walker reads the parent link only once the consumer's body has run, as the iterator did: TryGetValue can materialise a lazy resource, which runs generated XAML initialization from inside the loop and could re-parent the element being walked. When_ImplicitStyle_Nearest_Scope_Wins pins the order. The existing implicit-style tests define each key at a single level, so they pass even when the walk visits the application resources first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX
ResourceDictionaryWalker is a struct enumerator, and every call site stops at the first match, so the consuming foreach leaves the loop early. Without a Dispose the enumerator's stack slot keeps the ancestor and the dictionary it stopped on rooted past the loop; that retention is reported to slow Android runtime shards badly, where stack scanning is conservative. Implement IDisposable and null the four reference fields. For a struct enumerator implementing IDisposable, foreach emits a constrained call from a finally, so cleanup is guaranteed on every exit path and nothing is boxed. Checked against both early-exit shapes - break, and return from inside the loop body, which is what GetImplicitStyle does: Dispose runs exactly once, and the enumerator was still holding a live reference at that point. It cannot become a ref struct: GetResourceDictionaries still walks it with foreach from inside an iterator method. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX
Platform selection belongs in attributes rather than a #if, so discovery and filtering stay consistent across targets, and an issue-covering runtime test carries GitHubWorkItem metadata. The skip set is unchanged: NativeAndroid and SkiaAndroid together match the previous __ANDROID__ guard, since the enum has no combined Android alias. Verified the test still runs and passes on Skia Desktop rather than becoming silently skipped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX
002cf9c to
3ef368d
Compare
|
Claude finished @ajpinedam's task in 16s —— View job Re-review at
|
Thanks. I rebased onto master 1. 2. Android timeouts. Agreed, this is still open. Nothing on 3. Android skip. Agreed, and the original skip never applied. On |
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 241705 found UI Test snapshots differences: Details
|
|
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. |
GitHub Issue: closes #24522
PR Type:
🔄 Refactoring (no functional changes, no api changes)
What changed? 🚀
DependencyObject.GetResourceDictionariesreturns the ResourceDictionaries in scope, nearest first. It is a C# iterator, so every call allocates a state machine — including the very common case where no ancestor carries resources and the walk yields nothing. It runs once per{ThemeResource}reference (an object with N references performs N separate ancestor walks), twice per element Enter for the implicit-style lookup, and on every visual-tree resource retrieval.EnumerateResourceDictionariesnow returns a struct enumerator that performs that walk without allocating, and the three hot lookups use it: Phase A ofUpdateThemeReference,GetImplicitStyle, andResourceResolver.TryVisualTreeRetrieval. The iterator remains, but delegates to the walker, so the visit order — containing dictionary, then each ancestor's non-emptyResources, then the application resources — exists in exactly one place and the two.ToArray()callers are untouched.Two details worth calling out:
ResourceDictionary.TryGetValuecan hitTryMaterializeLazy, which runs a generatedResourceInitializerunder a pushed resolver scope — arbitrary XAML construction — from inside the loop body. Readingfe.Parentbefore yielding would have let a re-parent during materialization send the walk up a stale chain, resolving from the wrong ancestor scope. The failure mode there is a subtly wrong brush, not an exception.Given_Style.When_ImplicitStyle_Nearest_Scope_Winsdefines the same implicit style at application level and on a nearer ancestor and asserts the nearest wins. The pre-existing implicit-style tests define each key at a single level, so they would pass even if the walk were reordered or the application-resources tail dropped.Measured impact 📊
Managed bytes allocated per iteration on the UI thread (
GC.GetAllocatedBytesForCurrentThread, median of 7 rounds, two runs per side; reproduces within ~1 %):TextBoxButtonCheckBoxListViewItemToggleSwitchListView(2,000 items) scroll stepOver 1,000 scroll steps, so that the collection count resolves:
Each build reproduced its own gen0 count across runs, but a later master build measured 14 rather than 15, so the gen0 delta sits at the edge of this instrument's resolution; the byte figures are the reliable ones. The claim here is GC pressure, not frame time: wall-clock on the measuring machine varied by more than the effect between identical runs, so it is not reported.
Measured with a headless Skia app (
Uno.UI.Runtime.Skia.Headless) project-referencing the framework, with Fluent resources merged.Validation ✅
Runtime tests, Skia Desktop —
Given_Style,Given_ThemeResource,Given_ElementTheme,Given_ElementTheme_Resolution_Regression,Given_MergedAppResources_ThemeResource,Given_Theme_Materialization,Given_FrameworkElement_ThemeResources,Given_ResourceDictionary,Given_ResourceResolver,Given_VisualStateManager,Given_Storyboard,Given_MenuFlyout,Given_TextBlock,Given_Run,Given_Hyperlink,Given_Button,Given_CheckBox,Given_ToggleSwitch,Given_ListViewBase,Given_DependencyObjectCollection: 517 run, 509 passed, 15 skipped, 1 inconclusive, 7 failed.The 7 failures are the
Given_ListViewBaselayout-rounding/timeout set plusGiven_TextBlock.When_Inlines_Transitively_Change, all of which fail identically on a build of the merge-base without this change.The new test was checked against two deliberately broken walkers. With the walk skipping ancestor dictionaries entirely it fails, along with the two pre-existing implicit-style tests. With the walk visiting the application resources before the ancestors — an order inversion, which is the regression class this rewrite could actually introduce — it is the only test in
Given_Stylethat fails;When_ImplicitStyle,When_Style_Flows_To_PopupandWhen_StyleFailsToApplyall still pass. It also passes on a build of the merge-base, so it asserts behaviour this PR preserves rather than introduces.Perf axis: work removed 📊
This change trades an allocation for a struct walk, so the table above is the performance evidence: the CPU benefit is the GC pressure removed, not fewer instructions along the walk. Stated exactly, and deterministically:
GetResourceDictionaries/EnumerateResourceDictionariescallCPU time is deliberately not reported, and that is demonstrable rather than asserted. Re-measuring on this machine with a thread-cycle counter (
QueryThreadCycleTimesampled on the UI thread, which is where the work runs) showed that reversing the order of the two measurement phases flips the sign of the apparent result, and that the spread within a single phase reaches 74–97 % on the same build and workload. Any timing column produced here would report machine state rather than the change. Wall-clock is worse and is not reported either. The allocation figures above are unaffected: bytes are deterministic and reproduce to ~10 B on the low-variance workloads.Provenance. Measured with a headless Skia app (
Uno.UI.Runtime.Skia.Headless) project-referencing the framework, with Fluent resources merged; bytes viaGC.GetAllocatedBytesForCurrentThreadon the dispatcher thread, median of 7 rounds, two runs per side. Not BenchmarkDotNet — this repository has no BenchmarkDotNet harness, and the workload runs on the dispatcher thread, which is where the allocation counter has to be read.PR Checklist ✅
Screenshots Compare Test Runresults. — to check once CI has runFollow-ups this PR deliberately leaves open
UpdateAllThemeReferencesstill performs one full ancestor walk per theme reference; collapsing N walks into one is the larger win, but the surrounding code notes that updating one reference can cascade and modify the theme-reference map, and a newly resolvedStylecan change the ancestor scope mid-loop.GetResourceDictionaries(...).ToArray()callers inUpdateResourceBindingsstill allocate an array per theme update; they could rent fromArrayPool, asUpdateAllThemeReferencesalready does.ResourceResolver.TryVisualTreeRetrievalstill allocates a LINQ enumerator fromCurrentScope.Sources.FirstOrDefault()on this same path.ApplyStylesre-walks for an implicit style it usually already resolved; caching would remove the walks rather than cheapen them.🤖 Generated with Claude Code
https://claude.ai/code/session_012QzKQawubFcPPX9JSoZLkX
Internal tracking: unoplatform/uno-private#2349 (finding 6), under unoplatform/uno-private#2346.