Skip to content

Reduce temporary allocations while scrolling CollectionView on Android - #40881

Merged
kubaflo merged 2 commits into
mainfrom
simonrozsival-scroll-allocation-reduction
Nov 30, 2026
Merged

kubaflo merged 2 commits into
mainfrom
simonrozsival-scroll-allocation-reduction

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: bf7161cf0bffecc1f9dd08dd36d3b9ee9f4a968e

Dimension Assessment Rationale
Change confidence 8/10 ↑ Core unit tests all pass.
↑ Controls unit tests: 7,876 pass; the same 31 GC/leak tests fail on unmodified main.
↑ New regression tests cover re-entrant ApplyBindings, reused Grid structure, Grid measure that throws, and descendant event order.
↑ Allocation reduction measured on an Android emulator and in a BenchmarkDotNet run.
↓ Touches widely used paths (Element resources/descendants, ApplyBindings, Grid measure).
↓ No iOS, Mac Catalyst or Windows runtime validation; CI pending.

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

Description of Change

Follow-up to #40853. When a CollectionView cell is recycled on Android, TemplatedItemViewHolder.Recycle removes the templated view from the ItemsView's logical children and Bind adds it back. Each recycle therefore re-runs these steps over the cell's whole subtree, and the Grid is measured again:

  • resource propagation
  • stylesheet propagation
  • descendant/window propagation
  • binding-context propagation

Most of the garbage produced while scrolling comes from temporary objects on these paths, even when the app declares no stylesheets or resources. The changes keep the parent transitions and all semantics. They only stop creating throwaway objects:

  • Stylesheets (Element_StyleSheets, StyleSheetExtensions): no lists or yield iterators when there is nothing to apply. Ancestors are walked directly.
  • Resources (Element, ResourcesExtensions, ResourceDictionary, ResourcesChangedEventArgs):
    • Merged keys are collected without iterators.
    • Resolver delegates are cached.
    • No listener snapshot is taken when nothing listens.
  • Descendant events (Element): DescendantAdded/Removed are raised with a pooled breadth-first queue, in the same order as Descendants(). The queue is cleared before it is returned to the pool.
  • Bindings (BindableObject.ApplyBindings):
    • Returns early when nothing but BindingContext is bound.
    • Otherwise takes the same full snapshot as before, now in a cleared pooled array. Contexts that gain a binding during the pass are still reapplied.
  • Property propagation (PropertyPropagationExtensions): no ToArray() snapshot for zero or one child; otherwise a cleared pooled snapshot.
  • Grid (GridLayoutManager):
    • Structure arrays and span dictionaries are reused across measures.
    • A spare structure is double-buffered, so a measure that throws keeps the previous successful measurement for Arrange.
    • A re-entrant measure allocates its own structure.
  • Smaller sources:
    • Lazily created pending stacks in NavigationProxy replace eagerly allocated Lazy<T>s, which window propagation rebuilt on each detach.
    • Booleans are boxed through the cached boxes.
    • The cached click handler in SelectableItemsViewAdapter is reused instead of allocating a delegate on every bind.

The changes add no shared static scratch buffers that keep references alive: pooled arrays are cleared before they are returned. Event identity, ordering and re-entrancy snapshots are preserved.

Measurements

Workload:

  • Release Android CoreCLR, ARM64 API 35 emulator.
  • 10,000 items; each cell is a 3×2 Grid with a BoxView and three Labels, using typed bindings and MeasureAllItems.
  • 800 warm-up ScrollBy calls, then 4,800 measured calls per pass.
  • Allocation was counted on the calling thread.
main This PR Change
Allocated bytes per pass, uninstrumented 24,016,648 3,978,760 −83.4%
Gen0 GCs per pass 10–13 1–2
GC pause per pass 3.3–4.9 ms 0.6–1.1 ms
Thread CPU per pass, mean of 2 ABBA launch pairs × 5 passes 1,113 ms 987 ms −11% (suggestive only)

An earlier, noisier run of 10 launch pairs (host load 21–39) had a CPU difference whose bootstrap 95% confidence interval included zero. Treat the throughput gain as likely but not established; the GC time saved is only a few milliseconds per pass. dotnet-counters runs with the diagnostics build confirmed the same allocation and gen0 numbers.

New BenchmarkDotNet benchmark, ItemRecycleBenchmarker (remove, rebind, re-add and measure one cell; --job short, macOS arm64):

Mean Allocated per cell
main 3.62 µs 4.94 KB
This PR 2.88 µs 296 B

Remaining allocations

These were not changed, because removing them would require public API changes or would change semantics:

  • Public event args (ElementEventArgs, ParentChangingEventArgs, ItemsViewScrolledEventArgs).
  • The boxed Rect passed through the command mapper.
  • The resource-key snapshot taken in SetParent.
  • Platform objects such as ShapeDrawable.

Tests

  • BindableObjectUnitTests.BindingAddedToExistingContextWhileApplyingBindingsIsAppliedInSamePass: guards the ApplyBindings snapshot semantics.
  • GridLayoutManagerTests.ReusedManagerReflectsGridChanges: a reused manager must match a fresh one after changes to children, spans or definitions.
  • GridLayoutManagerTests.ThrowingMeasureKeepsPreviousMeasurementForArrange: guards exception safety.
  • ElementTests.DescendantEventsFollowDescendantsOrderForLargeSubtrees: guards event order across pooled-queue growth.

Validation:

  • dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj: passed.
  • dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj: 7,876 passed, 30 skipped, 31 failed. The same 31 GC/leak tests also fail locally on unmodified main.
  • Android Release build passed.
  • iOS, Mac Catalyst and Windows were not run locally.

Issues Fixed

No issue filed; this is a performance improvement.

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits.

Recycling a CollectionView cell removes the templated view from the
ItemsView's logical children and adds it back on bind, which re-runs
resource, stylesheet, window and binding-context propagation for the
whole cell subtree and re-measures its Grid. Make those paths avoid
throwaway objects:

- Skip stylesheet/resource iterator and HashSet allocations when there
  is nothing to apply and walk ancestors without yield iterators.
- Raise descendant events with a pooled breadth-first queue in the same
  order as Descendants().
- Cache resource-changed delegates and avoid listener snapshots when
  nothing listens.
- Snapshot bindings in ApplyBindings with a cleared pooled array and
  return early when only BindingContext is bound.
- Reuse GridLayoutManager's structure arrays across measures with a
  spare structure so a throwing measure keeps the previous measurement.
- Avoid per-bind closures in the Android SelectableItemsViewAdapter.

Adds an ItemRecycleBenchmarker that models the recycle/rebind/measure
sequence, and regression tests for re-entrant ApplyBindings, reused Grid
structure, exception-safe Grid measure and descendant event order.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 14:54
@github-actions

This comment has been minimized.

@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

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

The traversal queue grows without reclaiming consumed space, causing avoidable buffer rentals and array-clearing work for deep subtrees.

1 open issue
What changed in this PR

Follows up on #40853 by reducing temporary allocations in shared Controls and Core paths used during Android CollectionView recycling and scrolling.

Changes:

  • Pools temporary snapshots and traversal buffers, caches delegates and boxed booleans, and avoids unnecessary resource, stylesheet, and navigation allocations.
  • Reuses Grid measurement buffers while preserving the previous successful measurement if a later measure throws.
  • Adds regression tests for binding callbacks, descendant event order, and Grid state, plus a cell-recycling benchmark.
File Description
src/​Core/​tests/​UnitTests/​Layouts/​GridLayoutManagerTests.cs Tests Grid state changes and measurement exception safety.
src/​Core/​tests/​Benchmarks/​Benchmarks/​ItemRecycleBenchmarker.cs Benchmarks cell recycling, rebinding, and measurement.
src/​Core/​src/​Layouts/​GridLayoutManager.cs Reuses measurement structures and their buffers.
src/​Core/​src/​Handlers/​ViewHandlerExtensions.Android.cs Avoids allocating the default arrange delegate.
src/​Controls/​tests/​Core.UnitTests/​ElementTests.cs Tests descendant event order across queue growth.
src/​Controls/​tests/​Core.UnitTests/​BindableObjectUnitTests.cs Tests bindings added during binding application.
src/​Controls/​src/​Core/​VisualElement/​VisualElement.cs Skips unnecessary window-handler unsubscription.
src/​Controls/​src/​Core/​StyleSheets/​StyleSheetExtensions.cs Avoids stylesheet iterators on empty paths.
src/​Controls/​src/​Core/​ResourcesExtensions.cs Pre-sizes and directly fills merged resource-key sets.
src/​Controls/​src/​Core/​ResourcesChangedEventArgs.cs Exposes reusable resource resolver delegates.
src/​Controls/​src/​Core/​ResourceDictionary.cs Adds iterator-free resource-key collection helpers.
src/​Controls/​src/​Core/​NavigationProxy.cs Creates pending navigation stacks on demand.
src/​Controls/​src/​Core/​Internals/​PropertyPropagationExtensions.cs Pools child snapshots, with zero/one-child fast paths.
src/​Controls/​src/​Core/​Handlers/​Items/​Android/​Adapters/​SelectableItemsViewAdapter.cs Caches the selection click delegate.
src/​Controls/​src/​Core/​Element/​Element.cs Reduces resource, binding, and descendant propagation allocations.
src/​Controls/​src/​Core/​Element/​Element_StyleSheets.cs Avoids empty stylesheet lists and indexes visual children directly.
src/​Controls/​src/​Core/​BindableObjectExtensions.cs Uses cached boolean boxes when refreshing properties.
src/​Controls/​src/​Core/​BindableObject.cs Pools binding-context snapshots and skips passes without applicable bindings.

Review effort: Balanced

Comment on lines +1197 to +1202
var larger = ArrayPool<Element>.Shared.Rent(queue.Length * 2);
Array.Copy(queue, head, larger, 0, tail - head);
ArrayPool<Element>.Shared.Return(queue, clearArray: true);
queue = larger;
tail -= head;
head = 0;

@github-actions github-actions Bot 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.

Expert Review — 3 findings

Reviewed commit bf7161c.

See inline comments for details.

#if NETSTANDARD2_0
var keys = new HashSet<string>(StringComparer.Ordinal);
#else
var keys = new HashSet<string>(capacity, StringComparer.Ordinal);

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.

[moderate] Performance-Critical Path Optimization - Presizing sums entries before deduplicating resource keys. With ten merged dictionaries overriding the same 1,000 keys, each recycled-cell attachment now allocates a HashSet sized for at least 10,000 entries although it contains only about 1,000 distinct keys. The previous set grew with the distinct-key count; the new entry array can cross the large-object-heap threshold on current .NET targets. Bound the estimate or avoid presizing from the undeduplicated sum. The added benchmark has no overlapping resource dictionaries and misses this hot-path allocation regression.


if (tail == queue.Length)
{
var larger = ArrayPool<Element>.Shared.Rent(queue.Length * 2);

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.

[moderate] Performance-Critical Path Optimization - This grows the queue when its write index reaches the end, even if dequeuing has freed almost the entire buffer. For a single-child chain, only one element is pending, but visiting 1,000 nodes still grows the rented buffer from 16 to 512 slots. Every add/remove repeats the successive rents and clears the enlarged arrays, whereas the previous circular Queue retained its 16-slot capacity. Reuse the consumed space before growing, for example with circular indices or in-place compaction. The new test verifies order but not this narrow-subtree case.

SubColDefs(grid, CreateTestColumns("auto"));
SubstituteChildren(grid, view1);
SetLocation(grid, view1);
AssertMatchesFreshManager(grid, manager, view1);

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.

[moderate] Regression Prevention and Test Coverage - The test stops before reusing the structure that recorded the two-column span. Measures 1 and 3 use structure A, which never recorded a span; measure 2 records it in structure B. Consequently, removing _spans?.Clear() would still let this shrink assertion pass, despite leaving a stale two-column SpanKey that can index beyond the one-column definitions in ResolveSpan on B's next use. Repeat the final measure/fresh-manager comparison so the test actually exercises reuse of the populated span dictionary after shrinking.

@github-actions

Copy link
Copy Markdown
Contributor

Selected Tests

@kubaflo — AI-selected UI tests and device tests (GPT-6.2 Sol + MAI Code 2) for commit bf7161cf.

Result NOT QUEUED Platforms Android, iOS, MacCatalyst, Windows Tests all UI, 102 device Commit bf7161cf


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ❌ not queued all 77 categories —
Device tests ❌ not queued 102 of 105 units —
🧪 UI tests — the full suite on every platform

❌ Could not queue maui-pr-uitests: Azure Pipelines did not start maui-pr-uitests for the dispatch branch run-tests/pr40881-46447158154 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-uitests for the full suite.

GPT-6.2 Sol: Run the full UI suite on all four platforms because the Android scrolling optimization changes shared element, resource, and layout behavior.
MAI Code 2: Shared Controls and Core base classes plus Grid layout and Android CollectionView recycling require the full Controls and Core device suites on all platforms.

🧪 Running — 77 categories on Android, iOS, MacCatalyst, Windows

The complete maui-pr-uitests suite runs on every platform (same as /azp run).

🧪 Device tests — Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior +98 on Android, iOS, MacCatalyst, Windows

❌ Could not queue maui-pr-devicetests: Azure Pipelines did not start maui-pr-devicetests for the dispatch branch run-devicetests/pr40881-46447158154 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-devicetests for the full suite.

GPT-6.2 Sol: Run all Controls and Core device tests on all four platforms for shared element lifecycle and layout changes.
MAI Code 2: Shared Controls and Core base classes plus Grid layout and Android CollectionView recycling require the full Controls and Core device suites on all platforms.

🧪 Running — 102 categories on Android, iOS, MacCatalyst, Windows

Platform Categories
Android Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
iOS Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
MacCatalyst Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
Windows Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
⏭️ Skipped — what neither suite runs

Device tests — 3 categories, 0 platforms

Categories not run: Graphics, Essentials, BlazorWebView

Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.

🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)

UI tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android all categories all categories
iOS all categories all categories
MacCatalyst all categories all categories
Windows all categories all categories

GPT-6.2 Sol — Run the full UI suite on all four platforms because the Android scrolling optimization changes shared element, resource, and layout behavior.

  • Element, BindableObject, and VisualElement change shared binding, resource, stylesheet, and lifecycle propagation.
  • GridLayoutManager changes shared measure/arrange; the Android adapter and arrange edits do not make this an Android-only run.

MAI Code 2 — Shared Controls and Core base classes plus Grid layout and Android CollectionView recycling require the full Controls and Core device suites on all platforms.

  • Shared Element, VisualElement, BindableObject, resources/styles, and property-propagation changes have a cross-platform, base-class blast radius, so the UI run covers every platform and category.
  • GridLayoutManager reuses measurement structures and affects shared layout behavior, reinforcing a full UI run rather than only CollectionView tests.
  • The Android Items adapter changes exercise CollectionView recycling, but limiting tests to Android would miss the shared runtime changes.

Device tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
iOS Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
MacCatalyst Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay
Windows Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay

GPT-6.2 Sol — Run all Controls and Core device tests on all four platforms for shared element lifecycle and layout changes.

  • Shared Element, VisualElement, binding and resource changes warrant all Controls tests.
  • Shared Grid measure/arrange and Android ViewHandler arrange changes warrant all Core tests.
  • No Graphics, Essentials, BlazorWebView, or device harness changes.

MAI Code 2 — Shared Controls and Core base classes plus Grid layout and Android CollectionView recycling require the full Controls and Core device suites on all platforms.

  • Shared Element, VisualElement, BindableObject, resources/styles, and property propagation affect broad Controls behavior, selecting all Controls device-test units.
  • Shared GridLayoutManager changes affect Core layout behavior, selecting all Core device-test units.
  • The Android Items adapter is covered alongside the shared changes on Android; shared code requires iOS, Mac Catalyst, and Windows as well.
  • Graphics, Essentials, and BlazorWebView are unchanged, so those complete project suites are omitted.

Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

kubaflo added a commit that referenced this pull request Nov 30, 2026
…ths (#40902)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `584853032461f4bf7d3983bf37be87fb4cdb1955`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Android allocations drop by exactly
3,999 B per row bound (−20%) in 10 paired benchmark launches.<br>↑
Android screenshots of the benchmark are pixel-identical to `main`.<br>↑
Graphics device tests pass on Android 15 (39/39, including 6 new ones);
Core unit tests pass (1,411/1,411).<br>↑ Controls unit tests all pass
(7,909) with the leak-test fixes that `main` has since made
(#40882).<br>↑ An independent review found two issues; both are fixed
and the re-review was clean.<br>↓ The CPU and rebind-time gains aren't
significant on the emulator.<br>↓ Not built or run on Windows or run on
iOS; Mac Catalyst rendering wasn't checked visually.<br>↓ Controls
device tests and UI tests weren't run locally; CI is pending.<br>↓ Each
Android canvas keeps up to 4 pooled states with 3 Java paints each. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

On Android, every draw of a `BoxView` or another shape created about 21
Java `Paint`s, 2 Java `Path`s and 3 `PathF`s. A shape's view
(`MauiShapeView`) is a `PlatformGraphicsView`, which draws a
`ShapeDrawable` through a `ScalingCanvas` around the Android
`PlatformCanvas`:

- **Canvas states.** A draw resets the canvas state three times: the
view sets the canvas's `Canvas` before and after drawing, and resets the
`ScalingCanvas`. Each reset disposed the state and created a new one
with three new paints, and `PlatformCanvas.ResetState` then replaced
those with three more copies of the same defaults. `ShapeDrawable`'s
`SaveState` created one more state.
- **Paths.** `ShapeDrawable` clips to the shape's path and fills it. For
each, `ScalingCanvas` created a scaled copy of the `PathF`, and
`PlatformCanvas` converted the copy into a new Android `Path`.
- **BoxView.** `PathForBounds` built a new rounded-rectangle path for
every draw, with zero-radius curves when there are no rounded corners.

A `CollectionView` redraws a row's `BoxView` whenever the row is rebound
with a different color. In the [CollectionView scroll
benchmark](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark)
(on a branch for reference; not part of this PR), drawing it took 13% of
the UI thread's CPU samples and about 20% of its allocations. #40881
lists `ShapeDrawable` among the allocations it leaves.

#### Changes

**Microsoft.Maui.Graphics on Android**
- `PlatformCanvas` reuses canvas states. `AbstractCanvas` now releases
the states it no longer uses through a new `private protected virtual
ReleaseState`, which by default disposes them, as before.
`PlatformCanvas` returns them to its `PlatformCanvasStateService`. The
service keeps up to 4, and makes a released state a copy of the default
or saved state by copying paints with `Paint.Set` instead of creating
new ones. Only `PlatformCanvas` itself reuses states: subclasses can
reach the states' paints through `CurrentState`, so they still get new
states.
- `PlatformCanvas.ResetState` no longer replaces the paints of the state
it has just created with new copies of the same defaults.
- `PlatformCanvas` converts the paths it draws, fills or clips to into
one Android `Path` that it reuses. It converts again only for a
different path, a changed path or a different scale. To detect changes,
`PathF` gets an internal version that `Invalidate()` increments; all of
`PathF`'s mutators call it.
- `ScalingCanvas` passes its scale to `PlatformCanvas` (through the
internal `IScaledPathCanvas`) instead of creating scaled copies of
paths. Other canvases and `PlatformCanvas` subclasses still get scaled
copies.
- `AsAndroidPath` no longer allocates an enumerator.

**Core and Controls**
- A `BoxView` without rounded corners has a rectangle path.
- `ShapeDrawable` draws a path that the shape can reuse while its bounds
don't change. This is the internal `IShapeWithReusablePath`, which
`BoxView` implements by caching its path for the bounds and corner
radius. `ShapeDrawable` doesn't use it when it has a render transform to
apply to the path, or on Windows, whose canvas keeps device-dependent
geometry with the path. `IShape.PathForBounds` still returns a new path
every time.
- On Android, `UpdateShape` reuses the view's `ShapeDrawable`, reset to
how a new one starts, instead of creating a new one for every change of
the shape.

There are no public API changes.

#### Why it's safe

- A reused state is the same as the state that the old code created:
  - The copy constructor and the in-place copy share one routine.
- A reused default state is a copy of a template state that holds the
default paints.
- Font paints are copied the way `new TextPaint(Paint)` copies them,
which leaves the fields that `TextPaint` adds at their defaults.
- Shaders are cleared before a state is pooled, so pooled states don't
keep bitmaps alive.
- Android canvases copy the paths that they record or clip to, so
changing the reused Android `Path` doesn't change what was drawn before.
The conversion is keyed by a weak reference to the `PathF`, its version
and the scale; a conversion that throws is done again.
- Converting with the scale produces the same coordinates as converting
`AsScaledPath`'s copy.
- Nothing changes the reusable `BoxView` path: `ShapeDrawable` only
clips to it, fills it and strokes it. On iOS and Mac Catalyst, the
canvas now also reuses the `CGPath` that it caches on the path.
- `PlatformCanvas` subclasses and `BoxView` subclasses, which can
reimplement `IShape.PathForBounds`, keep the previous behavior.

#### Behavior changes

- Rendering doesn't change. On an Android emulator, screenshots of the
benchmark's rows are pixel-identical to `main`, both before and after
scrolling.
- Memory: an Android `PlatformCanvas` keeps up to 4 released states,
with 3 Java paints each, and one Android `Path` until it's disposed. A
`BoxView`'s canvas keeps one state more than before. In exchange,
drawing no longer creates Java objects.

#### Measurements

The benchmark scrolls a `CollectionView` of 1,000 items by 100 dp per
frame, for 240 frames per pass. Its row template is a `Grid` with a
`BoxView` whose `Color` is bound, 7 `Label`s, a `ProgressBar` and a
`CheckBox`. Each launch runs a cold pass, a warm-up pass and 5 warm
passes; a pass binds 267 rows.

Setup: Android 15 emulator (`sdk_gphone64_arm64`, Pixel 6 profile, 4
cores, 4 GB) on an Apple silicon Mac; Release; CoreCLR .NET
12.0.0-alpha.1.26523.103 (SDK 12.0.100-alpha.1.26523.103). `main`
bd40bc6 against 5a4448b, the first commit of this PR, in 10
interleaved launch pairs. Values are medians over the launches of each
launch's warm-pass median, with the median paired difference and its 95%
sign-test interval:

| Metric | `main` | This PR | Paired difference [95% CI] |
|---|---:|---:|---:|
| Allocated per row bound | 20,009 B | 16,010 B | **−3,999 B (−20.0%)**
[−3,999 .. −3,999] |
| UI-thread CPU time per row | 1,547.8 µs | 1,320.2 µs | −53.9 µs
(−3.5%) [−527.0 .. +188.3] |
| Rebind time per row | 265.6 µs | 217.3 µs | −7.8 µs (−2.9%) [−130.8 ..
+41.5] |
| Gen0 GCs per pass | 2 | 2 | 0 |
| Cold pass: allocated per row | 21,467 B | 17,482 B | −3,986 B [−4,168
.. −3,981] |
| Cold pass: methods JIT-compiled on the UI thread | 54 | 60 | +6 |
| Cold pass: methods JIT-compiled on all threads | 4,092 | 3,794 | −290
[−509 .. −193] |

- The time intervals include zero: on this emulator, the benchmark can
only resolve changes of about 20%.
- The second commit only changes how subclasses and font paints are
handled. In 2 more launch pairs, it allocated the same 16,010 B per row.
- EventPipe sample-profiler traces of 8 warm passes (2,136 rows; one
trace each, of `main` and of the final commit):
`PlatformGraphicsView.Draw` dropped from 187 to 35 UI-thread samples
(13.0% → 3.0%), and from 20.1% to 0.6% of the UI thread's sampled
allocations. Within it, `AbstractCanvas.ResetState` dropped from 66
samples to 2, `Paint` constructors from 42 to 0, and `AsAndroidPath`
from 28 to 0.
- Mac Catalyst (Apple silicon, 18 cores, 2 launch pairs of the final
commit): allocations dropped from 29,207 to 28,240 B per row (−967 B).
UI-thread CPU time per row was 9.6% and 7.7% lower in the two pairs, but
two pairs are too few for an interval.

#### Tests

New tests:
- `BoxViewUnitTests` (Controls): the path without rounded corners is a
rectangle; one rounded corner gives a rounded path; the reusable path is
kept until the bounds or the corner radius change; a subclass's
`PathForBounds` is used.
- `ShapeDrawableTests` (Core): the shape's reusable path is drawn; a
render transform isn't applied to it.
- `PlatformCanvasTests` (Graphics device tests, Android): saving,
restoring and resetting states doesn't allocate; reused states start
from their prototype (color, alpha, gradient shader and shadow don't
carry over); a changed path is converted again; the winding mode follows
each fill; `ScalingCanvas` clips to and fills scaled paths, and passes
scaled copies to subclasses.

Commands, with `.dotnet` linked to the SDK from `global.json`:
- `.dotnet/dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj`,
then
`artifacts/bin/Core.UnitTests/Debug/net12.0/Microsoft.Maui.UnitTests`:
1,411 passed, 0 failed.
- `.dotnet/dotnet build
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`, then
`artifacts/bin/Controls.Core.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.Core.UnitTests`:
7,878 passed, 30 skipped, 31 failed. The 31 are GC leak tests (tests
named `*DoesNotLeak*`, `CommandsSubscribedToCanExecuteCollect` and three
`TransformGroupTests`). The same 31 fail on `main` bd40bc6's sources,
where 7,874 pass without the 4 new tests, and #40882 has since fixed
them on `main`. With #40882's test changes applied to this branch: 7,909
passed, 30 skipped, 0 failed.
- `pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1
-Project Graphics -Platform android -DeviceUdid emulator-5600
-DotnetPath .dotnet/dotnet`: 39 passed, 0 failed, on the Android 15
emulator, including the 6 new tests.
- `.dotnet/dotnet format whitespace --folder --include <changed files>
--verify-no-changes`: no changes.
- Builds without errors or warnings (warnings are errors in this repo):
Graphics for `net12.0`, `net12.0-android37.0`, `net12.0-ios27.1` and
`net12.0-maccatalyst27.0`; Core and Controls for `net12.0` and
`net12.0-android37.0`; and Release builds of the benchmark for Android
and Mac Catalyst, which validate the PublicAPI files.
- Benchmark, from the benchmark branch: `Build-ScrollBenchmark.ps1
-Variant fix -Platform android -MauiRoot <this checkout>`,
`Invoke-ScrollBenchmark.ps1 -Variants base,fix -Platform android -Rounds
10 -Serial emulator-5600` and `Compare-ScrollBenchmark.ps1
<results>.jsonl -Baseline base -Candidate fix`.

Not run:
- Windows: not built or run. The shared code compiles for `net12.0`,
Windows-specific code is unchanged, and `ShapeDrawable` doesn't reuse
paths on Windows.
- iOS: not run. Mac Catalyst: the benchmark ran, but its rendering
wasn't checked visually.
- Controls device tests (`BoxViewTests`, `ShapeTests`), UI tests,
physical Android devices and other Android API levels.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No issue filed; this is a performance improvement. Related: #40881
(fewer temporary allocations while scrolling a `CollectionView` on
Android; no files in common), and #39909 and #39914 (deterministic
disposal of Android Graphics objects, which this keeps).

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
…p the zero-spacing item decoration (#40901)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `949b79d0638d22483c94bae3f804090cd6646aca`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Android CollectionViewTests and
CarouselViewTests pass on this revision: 314 passed, 1 skipped by its
attribute, 0 failed (Android 15 emulator).<br>↑ New device tests cover
the selection of recycled rows (Single and Multiple, default color and
Selected visual state) and spacing changes between zero and non-zero
(linear in both orientations, grid).<br>↑ A trace shows the removed work
gone (selection 2.2% and GetItemOffsets 0.8% of UI-thread samples, both
to 0), with allocations unchanged.<br>↓ No speed-up is measurable on the
emulator, and the A/B included a third commit that is no longer part of
this PR.<br>↓ Android UI tests, CI and physical devices not run
yet.<br>↓ OnSelectedChanged is no longer called on bind or recycle when
the selection doesn't change, which a custom SelectableViewHolder
subclass could notice. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This is .NET 12 performance work, so it targets `main`.

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

When a CollectionView scrolls on Android, every row that comes into view
is bound and every row that leaves it is recycled. Two parts of that
work called into Java (or were called from Java) for every row without
changing anything. This PR removes those calls. What the user sees
doesn't change.

#### 1. Don't reapply an unchanged selection

Files: `SelectableViewHolder.cs`, `SelectableItemsViewAdapter.cs`,
`TemplatedItemViewHolder.cs`

`SelectableItemsViewAdapter` sets `SelectableViewHolder.IsSelected` for
every item it binds and every holder it recycles. The setter always
applied the value:
- It set the item view's `Foreground`, `Background`, `Activated` and
`Selected`. Each of these is a JNI call after a JNI read of
`ViewHolder.ItemView`.
- It scanned the content's visual state groups and set `IsItemSelected`.

With `SelectionMode.None` the value is always `false`. So for every row
it scrolled, a list made 8 JNI field reads (with peer lookups) and 8 JNI
property sets that changed nothing.

Binding and recycling now call a new internal `UpdateIsSelected`, which
skips a value that the item view and its content already show.
- A holder applies its selection the first time it is bound.
- It applies it again after `TemplatedItemViewHolder` replaces its
content: new content isn't selected yet, and its visual states decide
whether the default selection color applies.
- Selection changes still set `IsSelected` as before:
`MarkPlatformSelection`, `ClearPlatformSelection` and clicks, including
the unconditional re-sync from #31591. The public `IsSelected` setter is
unchanged.

#### 2. No item decoration without item spacing

File: `MauiRecyclerView.cs` (`UpdateItemSpacing`)

`UpdateItemSpacing` always added a `SpacingItemDecoration`, even when
the spacing is zero, which is the default. Its `GetItemOffsets` then
offsets nothing. RecyclerView still calls it from Java for every row it
binds, and each call looks up the peers of its four arguments and calls
back into Java for `base.GetItemOffsets`.

Now no decoration is added without spacing; the RecyclerView's padding
is still reset as before.
- Changing the spacing to or from zero removes or adds the decoration.
- A decoration from an overridden `CreateSpacingDecoration` is always
added, including a subclass of `SpacingItemDecoration`.
- CarouselView uses its own decoration and is not affected.

#### Why it's safe

- **Selection:** the check only skips writing values that are already
applied. It is reset whenever a holder's content is replaced. Holders
that RecyclerView keeps in its view cache stay in `_currentViewHolders`,
so selection changes still reach them.
- **Decoration:**
- A decoration whose offsets are all zero has the same effect as no
decoration.
- RecyclerView's `willNotDraw` stays `false`, because CollectionView
doesn't set `OverScrollMode.Never`.
- `InvalidateItemDecorations()` becomes a no-op when there's nothing to
invalidate.

#### Behavior changes

- `SelectableViewHolder.OnSelectedChanged()` (protected virtual) is no
longer called when binding or recycling a holder doesn't change its
selection. A custom subclass that used it as a per-bind hook would see
fewer calls.
- Selection visuals are reapplied only when the selection changes or the
holder's content is replaced, not at every bind.
- With zero spacing, `MauiRecyclerView.ItemDecorationCount` is 0 instead
of 1.

#### Results

The numbers come from the CollectionView scroll benchmark
([source](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark),
pushed for reference; it isn't part of this or any PR).
- What it scrolls: a CollectionView of 1,000 items. Each row is a Grid
with a BoxView, 7 Labels, a ProgressBar and a CheckBox, with 13 compiled
bindings and the default `SelectionMode.None` and zero spacing.
- How it scrolls: 100 dp per frame for 240 frames per pass, which binds
about 267 rows per pass.
- Method: base and candidate launches are interleaved. Each launch is
reduced to the median of its 5 warm passes, launches are paired by
round, and the result is the median paired difference with a 95%
sign-test interval.

Setup:
- Base is main bd40bc6.
- The candidate is this PR plus a third commit that coalesced layout
requests during a rebind. I dropped that commit from this PR because it
added machinery to Core without a measurable gain. **So the A/B measured
all three changes together.**
- Device: an Android 15 emulator (Pixel 6 profile, android-35
google_apis arm64-v8a, 4 cores, 4 GB) on a shared, heavily loaded Mac
(load average 15–64).
- Runtime: CoreCLR .NET 12.0.0-alpha.1.26523.103, Release builds.

**Allocations are unchanged:** 20,009 B/row in both (difference 0 [0 ..
0]), with 2 gen0 GCs per pass.

**Timing: no significant difference.** The emulator resolves only
differences of about 20% or more.

| Run (rounds) | Rebind, UI-thread CPU per row | UI-thread CPU per row |
Wall time per pass |
|---|---|---|---|
| 1, vs main build (12) | +5.5% [−24.1 .. 56.1 µs] | +7.5% [−70 .. 390
µs] | +20.6% [34 .. 2,584 ms] * |
| 2, vs main build, reversed order (12) | +6.6% [−17.0 .. 28.8 µs] |
+8.8% [−116 .. 170 µs] | +0.7% [−81 .. 211 ms] |
| 3, vs main built in the same checkout (10) | +1.5% [−15.9 .. 10.6 µs]
| −2.6% [−88.6 .. 60.8 µs] | 0.0% [−86 .. 3 ms] |
| 3, control: main vs main, two builds (10) | +2.8% [−3.1 .. 15.6 µs] |
+2.6% [−22.0 .. 139.8 µs] | +0.1% [−1 .. 85 ms] |

In run 1, the candidate's slow passes also took more UI-thread CPU for
the same rows. That points to the emulator losing CPU to the host rather
than to the change, and runs 2 and 3 didn't reproduce it. Run 3's
control shows the same small lean between two builds of the same commit.

**Trace evidence for the two changes in this PR.** I traced the
candidate with the EventPipe sample profiler over 8 warm passes (2,136
rows) and compared it with a trace of main. The traces were taken at
different times, so compare shares, not totals.

| UI-thread samples | main | candidate |
|---|---|---|
| Total | 1,434 | 1,095 |
| `SelectableViewHolder` frames (`SetSelectionStates`, the `IsSelected`
setter) | 32 (2.2%) | 0 |
| … of which JNI reads of `ViewHolder.ItemView` (`GetObjectField`) | 18
(1.3%) | 0 |
| `SpacingItemDecoration.GetItemOffsets`, called from Java | 11 (0.8%) |
0 |

Per bound row, the two changes remove:
- 8 JNI property sets and 8 JNI field reads, when the selection doesn't
change;
- 1 call from Java into .NET with 4 peer lookups, plus 1 call back into
Java, when there's no spacing.

#### Tests

New device tests in `CollectionViewTests.Android.cs`:
- `RecycledItemsShowTheirOwnSelection` (4 cases). Single and Multiple
selection, each with the default selection color and with a template
that colors selection through a `Selected` visual state. It scrolls so
that rows are recycled, changes the selection while the selected item is
out of view, and turns selection off. Every row in view must show the
selection of the item it is bound to: `IsSelected`, `Activated`,
`Selected`, `IsItemSelected`, the default color and the visual state.
- `LinearItemSpacingChangesBetweenZeroAndNonZero` (vertical,
horizontal). It checks the decoration count and item bounds as the
spacing goes 0 → 40 px → 0 → 40 px.
- `GridItemOffsetsExcludeCrossAxisOuterSpacing` (existing, 4 cases) now
also checks the decoration count and the non-zero → zero transition.

Run on this revision, on an Android 15 (API 35) emulator, Release:

```
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -DeviceUdid emulator-5620 -DotnetPath $PWD/.dotnet/dotnet -IncludeClasses 'Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CarouselViewTests' -Timeout 01:30:00
```

Result: **Passed.** 315 total, 314 passed, 1 skipped
(`CellSizeAccountsForMargin`, skipped by its attribute), 0 failed.

`dotnet format whitespace --folder --verify-no-changes` on the changed
files reports nothing new. `SelectableItemsViewAdapter.cs` has 27
whitespace issues that are also on main; I left them, because #40881
reformats that file.

Not run:
- Android UI tests (Appium), including the selection screenshot tests;
left to CI.
- Physical devices.
- iOS, Mac Catalyst and Windows, which these Android-only files don't
affect.
- Unit tests, since no shared code changed.

#### Overlap with #40881

#40881 also edits `SelectableItemsViewAdapter.cs`. Merging the two
conflicts in `OnViewRecycled`, where each PR changes one of two adjacent
lines. The bind path merges cleanly. The resolution keeps both:

```csharp
selectable.Clicked -= SelectableClickedHandler;
selectable.UpdateIsSelected(false);
```

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None; this was found by profiling.

Related:
- #40881 also edits `SelectableItemsViewAdapter.cs`; see above.
- #40318 (inflight/11.0.1xx-sr3) composes with the decoration change:
its checks treat a missing decoration like a zero-spacing one.
- #37337 is opt-in handler update batching.
- #31591 re-syncs selection on click; that path is unchanged here.
- #38969 and #39661 also changed the spacing decoration (its cost and
its outer-edge spacing).

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
…every arrange (#40900)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `ae55c95de66d091dccc25bde12a8462f12b2941b`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ The allocation savings are exact and
reproduced on Android and Mac Catalyst, 8 interleaved rounds each.<br>↑
21 new unit tests cover notification order, SizeChanged, IsSet,
allocations and 9 kinds of Frame customization; deliberate mutations of
the arrange change were caught.<br>↑ On a local merge with main
18ccee2, Core.UnitTests (1,484 passed) and Controls.Core.UnitTests
(7,927 passed, 30 skipped) had 0 failures and 0 warnings.<br>↓ The
Windows one-line change wasn't compiled locally; CI is pending.<br>↓
Device and UI tests weren't run locally. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

Each layout pass boxes doubles and a `Rect` that nothing reads. This PR
removes those allocations in two commits. Neither commit adds public
API.

#### 1. Don't box unchanged bounds components (1357b92)

`VisualElement.UpdateBoundsComponents` sets `X`, `Y`, `Width` and
`Height` through their read-only bindable properties whenever the frame
changes. That boxes all four doubles, including the components that
didn't change. Setting an equal value raises no notifications, so those
boxes become garbage immediately. #34155 traced this boxing and deferred
it to #34080.

The private setters now call a new internal
`BindableObject.SetValueIfChanged(BindablePropertyKey, double)`. It
returns without boxing only when `SetValue` would change nothing:

- the property already holds a value with `ManualValueSetter`
specificity and identical bits, so `+0`/`-0` and NaN payloads still go
through `SetValue`;
- the property isn't being set at that moment, so re-entrant sets are
still queued;
- the property has no dynamic resource and no default value creator.

Every other write goes through `SetValue` as before. That includes the
first write, which marks a component that keeps its default value as
set.

#### 2. Don't box the frame for the built-in `Frame` command
(ae55c95)

After every platform arrange, `PlatformArrangeHandler` (Android, iOS/Mac
Catalyst, Windows) invokes the `IView.Frame` command with the frame.
That boxes the `Rect` (48 bytes), although the built-in mapping,
`ViewHandler.MapFrame`, ignores its args. #40881 left this boxing in
place, among allocations whose removal it expected to need public API
changes or to change semantics; this change needs neither. The arrange
pass now calls the new internal `ViewHandler.InvokeFrame`, which boxes
the frame only when something might read it.

**Design point for reviewers.** `CommandMapper` is public. Apps and
libraries can replace or append to the `Frame` mapping and read its
args, and that has to keep working:

- `CommandMapper.FrameworkCell` is the cell through which sealed
framework commands are remapped in place. It now remembers the command
it was built with. `RunsBuiltIn(command)` is true only when `command` is
the cell's mapping and no lazy framework remap
(`ModifyFrameworkMapping`) has replaced it.
- `ViewHandler.BuiltInFrameCommand` captures the `Frame` cell of
`ViewCommandMapper` during `ViewHandler`'s static initialization, before
app code can change the mapper.
- `CommandMapper.InvokeBoxingArgsIfRead<TArgs>` resolves the command the
same way `Invoke` does, with the same `CanInvokeMappers` check and
direct `GetCommand` resolution. It passes `null` only when the resolved
command still runs the built-in cell. Any other command gets the boxed
args.
- Every customization resolves to a different delegate, so it still gets
the boxed `Rect`. This covers:
- `AppendToMapping`, `PrependToMapping`, `ModifyMapping`,
`ReplaceMapping` and the indexer, on a handler's mapper or on
`ViewCommandMapper`;
  - a replaced `ViewCommandMapper` or handler `CommandMapper`;
  - a `GetCommand` override;
  - a Controls lazy remap of `Frame` (Controls has none today).
- `ElementHandler.Invoke` is public virtual, so a handler subclass could
override it and read the args of any command.
- `InvokeFrame` takes the new path only for handler types declared in
Microsoft.Maui. It decides this once per handler, from
`GetType().Assembly`, because detecting the override itself would need
reflection that isn't trim-safe.
- All other handlers call `Invoke` with the boxed frame as before:
Controls handlers, app and library handlers, and other `IViewHandler`
implementations.
- A unit test checks that no handler type in Microsoft.Maui overrides
`Invoke`.

Alternatives I tried and dropped:

- **A cached box per handler.** Frames mostly change on rebind, and it
would keep 48 bytes alive for every handler.
- **Checking the command first, then calling `Invoke(Frame, null)`.**
That resolves the command twice.
- **Taking the new path for Controls handler types too.** Possible, but
an `Invoke` override added to one of them later would silently lose the
frame.

#### Behavior changes

- The built-in `MapFrame` now receives `null` args instead of the frame.
It never read them. Every customized `Frame` command and every `Invoke`
override still receives the boxed `Rect`.
- `X`, `Y`, `Width` and `Height` behave the same:
PropertyChanging/PropertyChanged and their order, `SizeChanged`,
`SizeAllocated`, `IsSet` and handler updates.
- The `Frame` saving applies to handler types declared in
Microsoft.Maui, which covers all built-in Core handlers. Controls
handler types (for example `CollectionViewHandler`) and app-defined
handler subclasses still box the frame.

#### Results

The numbers come from the [CollectionView scroll
benchmark](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark),
which is pushed for reference and isn't part of this PR.

- **Workload:** a CollectionView of 1,000 items, scrolled
programmatically by 100 dp per frame. Each row is a Grid of 11 views
with 13 compiled bindings.
- **Comparison:** main bd40bc6 against this PR's head, 8 interleaved
rounds per platform.
- **Each launch:** 1 cold pass, 1 warm-up pass and 5 warm passes. Each
launch is reduced to the median of its warm passes.
- **Statistics:** medians, and the paired difference with a 95%
sign-test interval.
- **Allocations:** bytes allocated on the UI thread, which are exact for
a given build.

| | Android emulator | Mac Catalyst |
|---|---|---|
| Device, OS | Pixel 6 AVD, Android 15 (API 35, google_apis arm64), 4
cores, 4 GB | Apple M5 Max (18 cores), macOS 26.7.3 |
| Runtime, SDK | CoreCLR 12.0.0-alpha.1.26523.103, SDK
12.0.100-alpha.1.26523.103 | same |
| **Allocated per row** | **20,009 → 18,945 B (−1,064, −5.3%)** |
**29,207 → 27,648 B (−1,559, −5.3%)** |
| … from the bounds commit¹ | −568 B (≈24 boxed doubles) | −789 B (≈33
boxed doubles) |
| … from the `Frame` commit¹ | −496 B (≈10 boxed `Rect`s) | −770 B (≈16
boxed `Rect`s) |
| Allocated per row, cold pass | −1,057 B [−1,242 .. −873] | −1,106 B
[−1,106 .. −1,106] |
| Allocated during startup | −1,796 B [−11,792 .. 53,192] | −60,024 B
[−76,664 .. −31,576] |
| Gen0 GCs per pass | 2 → 2 | 1 → 1 |
| Rebind per row: medians; paired difference | 247.7 → 257.9 µs; −33.1
[−384.3 .. 138.2] | 625.3 → 632.4 µs; +0.9 [−39.2 .. 27.9] |
| UI-thread CPU per row: medians; paired difference | 1,515.9 → 1,554.3
µs; −113.8 [−868.3 .. 353.6] | 3,054.0 → 3,128.4 µs; +33.7 [−151.4 ..
166.5] |

¹ From 2 extra launches of a build of 1357b92 alone. Allocations are
exact, so 2 launches are enough.

These runs can't resolve a timing change: every interval includes zero.
On this emulator, the benchmark resolves only changes of about 20% or
more, and the Mac was a shared, loaded host.

#### Tests

New tests:

- **Controls.Core.UnitTests, `VisualElementTests`** (8 cases):
- For 6 frame changes, PropertyChanging/PropertyChanged fire only for
the components that changed, in X, Y, Width, Height order. `SizeChanged`
follows only when the size changed.
  - The first frame still marks unchanged components as set.
- 100 width-only frame changes box at most one double each. This test
fails on main, where 100 updates allocate 9,600 B.
- **Core.UnitTests, `CommandMapperExtensionTests`** (11 cases):
- Invoking the built-in `Frame` command through a mapper chained to
`ViewCommandMapper` allocates 0 bytes.
  - The unmodified built-in command gets `null`.
- A `Frame` mapping that reads args gets the boxed `Rect` for 9 kinds of
customization, including lazy framework remaps and a `GetCommand`
override.
- **Core.UnitTests, `AbstractViewHandlerTests`** (2 cases):
  - An `Invoke` override still gets the `Rect`.
  - No handler type in Microsoft.Maui overrides `Invoke`.

I also checked that two deliberate mutations of the arrange change are
each caught by the intended test: ignoring lazy framework remaps, and
ignoring `Invoke` overrides.

Commands and results, on a local merge of this branch with main
18ccee2:

- `dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj`: 0
warnings, 0 errors (`TreatWarningsAsErrors` is on).
- `dotnet build
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`: 0
warnings, 0 errors.
- `dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj
--no-build`: passed (1,484 passed, 0 failed).
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--no-build`: passed (7,927 passed, 30 skipped, 0 failed).
- `dotnet format whitespace --folder --include <changed files>
--verify-no-changes`: no changes.
- The Android, iOS and Mac Catalyst builds of Core and Controls compiled
as part of the benchmark builds.

Not run:

- **Windows:** `ViewHandlerExtensions.Windows.cs` gets the same one-line
change as Android and iOS, but I couldn't compile it on this Mac (no
Windows SDK). CI will.
- **Device and UI tests.** For example,
`ViewHandlerTests.PlatformArrangeTriggersMapFrame` counts `Frame`
invocations through `AppendToMapping`.
- **iOS benchmark.** iOS shares `ViewHandlerExtensions.iOS.cs` with Mac
Catalyst, which was measured.

#### Related work and conflicts

- Draft #40798 (typed `BindableProperty<T>` storage) rewrites the same
four `X`/`Y`/`Width`/`Height` accessors (typed getters, `SetValue` →
`SetValueTyped`). Against its branch (3f40772), `BindableObject.cs`
merges cleanly, and `VisualElement.cs` conflicts in exactly those four
accessors: 4 hunks of 2 lines each. Whichever PR lands second resolves
them. Typed storage removes the box itself; skipping unchanged
components still saves the `SetValue` work.
- #40881 (`BindableObject.cs`, `VisualElement.cs`,
`ViewHandlerExtensions.Android.cs`) and #40884 (`BindableObject.cs`)
also change these files; both branches merge cleanly with this one.
- #35144 (closed) proposed approximate `Frame` equality for #35142. This
PR keeps the bit-exact comparison the `Frame` setter uses today, so the
two don't interact.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None. Related: #34080 (value-type boxing in `BindableObject.SetValue`),
#34154 (allocations in the layout engine).

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
…ng only when something uses them (#40896)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `ca4a1c046566a164211ecc150ee188c142d068df`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ `Scrolled` event args matched main's
algorithm on all 1,810 callbacks across 9 layouts (temporary check, not
committed).<br>↑ New Mac Catalyst device tests pass; the "nothing
listens" case fails on main, and two broken variants of the skip path
fail the delta test.<br>↑ Controls unit tests for ItemsView,
CollectionView, CarouselView and SwipeView: 96/96 pass.<br>↑ Benchmark
over 12 paired rounds: −4,028 B/row (exact) and −4.9% UI-thread CPU
[−8.2% .. −2.9%].<br>↓ Subclasses of `ItemsViewDelegator2` that override
`GetVisibleItemsIndex` or `GetVisibleItemsIndexPath` are no longer
called on scroll when nothing listens.<br>↓ A broad Mac Catalyst
device-test run under heavy host load had 2 timing failures; both passed
in isolation and weren't rerun on main.<br>↓ Not run on an iOS simulator
or device; CI pending. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

On iOS and Mac Catalyst, `ItemsViewDelegator2.Scrolled` found the
visible items on every scroll callback. It sorted
`IndexPathsForVisibleItems` with LINQ (`OrderBy`/`ThenBy`/`ToList`),
asked the layout for the attributes of everything in the viewport,
queried and sorted `IndexPathsForVisibleItems` a second time for the
center item's fallback, and wrapped every attribute and index path in a
new managed peer. It did all that even when nothing read the result: no
`Scrolled` handler, no `OnScrolled` override, and
`RemainingItemsThreshold` at its default of -1. In a Mac Catalyst trace
of the [CollectionView scroll
benchmark](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark)
on main, which has no `Scrolled` subscriber, that was about 10% of the
UI thread's allocations and 6% of its CPU time.

**Changes**

- `ItemsViewDelegator2.Scrolled` finds the visible items only when the
`Scrolled` event (a handler, or an override of `ItemsView.OnScrolled`)
or the remaining items threshold uses them. Otherwise it only updates
the offsets that the deltas of the next `Scrolled` event are measured
from, exactly as before: the content offset plus the inset, or 0 while
no item is visible (#34153). It checks for visible items with
`VisibleCells.Length`. That counts the same cells as
`IndexPathsForVisibleItems`, but the cells already have managed peers,
which the index paths would need new ones for.
- When the visible items are needed, they're found without LINQ: one
pass over `IndexPathsForVisibleItems` finds the first and last items by
section and row, and the first by row (the center's fallback), breaking
ties the way the stable sorts did. The second
`IndexPathsForVisibleItems` query is gone. The layout-attribute scan
(#34240, #33719, #40131) is unchanged, except that it reads each
attribute's frame and index path once.
- `ItemsView.HasScrolledObservers` (internal) is true when `Scrolled`
has a handler or `OnScrolled` is overridden. The override check is
cached and works like `Page.HasBackButtonPressedOverride`, through a
delegate to the virtual method, which is safe for trimming and AOT. If
the declaring type couldn't be read, the check counts as an override and
takes the full path.

No public API changes.

**Why it's safe**

- Only `ItemsView.SendScrolled` (the `Scrolled` event and `OnScrolled`)
and the threshold check read the visible items:
- CarouselView takes its position from the compositional layout's
`VisibleItemsInvalidationHandler`, and `CarouselViewDelegator2.Scrolled`
still updates `IsScrolling` after `base.Scrolled`.
- SwipeView and the Shell flyout subscribe to `Scrolled`, so they take
the full path.
  - No built-in `ItemsView` subclass overrides `OnScrolled`.
  - The scroll anchor still runs first.
- Whenever something listens, the event args are the same as before. A
handler that subscribes later gets the same first deltas too.
- The threshold behavior and its re-entrancy guard (#40578) are
unchanged.

**Behavior change for subclasses**

When nothing listens, `Scrolled` no longer calls the protected virtual
`GetVisibleItemsIndex` and `GetVisibleItemsIndexPath`. A subclass of
`ItemsViewDelegator2` that overrides them to observe scrolling isn't
called then. Overrides of `Scrolled` itself still run on every callback.

**Results**

The benchmark scrolls a CollectionView of 1,000 items with a 13-binding
row template on every frame. Release builds of main bd40bc6 (`base`)
and this PR ca4a1c0 (`fix`) ran on Mac Catalyst (macOS 26.7.3, M5
Max, 18 cores, CoreCLR .NET 12.0.0-alpha.1.26523.103, SDK
12.0.100-alpha.1.26523.103):
- 12 interleaved rounds, a fresh process per launch, alternating the
order.
- Each launch is reduced to the median of its 5 warm passes.
- Paired medians of the differences, with 95% sign-test intervals.
- The host's load average was 43–65 during the run, so the timing
intervals are wide.

| Per row bound, warm passes | main | this PR | Difference [95% CI] |
|---|---|---|---|
| Allocated by the UI thread | 29,207 B | 25,178 B | −4,028 B (−13.8%),
exact |
| Gen0 GCs per pass | 1 | 0 | −1 |
| GC pause per pass | 2.8 ms | 0.0 ms | −2.8 ms [−3.1 .. −2.7] |
| UI-thread CPU | 3,275.9 µs | 3,105.6 µs | −161.7 µs [−269.3 .. −94.1]
(−4.9%) |
| Frame interval p50 / p95 | 16.7 / 16.7 ms | 16.7 / 16.7 ms | 0 |
| Cold pass: allocated per row | 49,717 B | 37,870 B | −11,847 B
(−23.8%), exact |
| Cold pass: UI-thread CPU | 1,737.9 ms | 1,654.3 ms | −65.9 ms [−110.0
.. −44.3] |
| Cold pass: methods JIT-compiled or prepared by the interpreter on the
UI thread | 5 | 1 | −4 |

Rebind time per row also came out 18.8 µs lower [−29.9 .. −1.2].
`Scrolled` isn't part of the rebind, so that's probably the missing GC
pause plus noise; I don't claim it.

The benchmark has no `Scrolled` subscriber. To measure the path with
one, a temporary device test (not committed) timed
`ItemsViewDelegator2.Scrolled` itself on Mac Catalyst:
- Release device-test app; a CollectionView of 1,000 labels with 12
visible.
- 240 non-animated scrolls of 100 pt, each followed by `LayoutIfNeeded`;
medians of 6 rounds.
- Bytes from `GC.GetAllocatedBytesForCurrentThread`; wall-clock time
under host load.

| Per `Scrolled` callback | main | this PR |
|---|---|---|
| Nothing listens | 2,251 B, 127.8 µs | 123 B, 10.9 µs |
| A `Scrolled` handler | 2,251 B, 127.5 µs | 309 B, 80.0 µs |

The 123 B left when nothing listens is the `VisibleCells` array.

**Tests added**

- `ItemsViewTests.HandlersOfScrolledObserveScrolled` and
`OverridesOfOnScrolledObserveScrolled`: unit tests for
`HasScrolledObservers`.
-
`CollectionViewTests.ScrolledFindsTheVisibleItemsOnlyWhenSomethingUsesThem`
(iOS and Mac Catalyst device test) counts calls to
`GetVisibleItemsIndex`, with 4 cases: nothing listens, a `Scrolled`
handler, an `OnScrolled` override, `RemainingItemsThreshold`. On main,
the "nothing" case fails (expected 0, actual 1).
-
`CollectionViewTests.ScrolledMeasuresDeltasFromScrollsNothingListenedTo`
(iOS and Mac Catalyst device test) checks the offset and delta of the
first event a late handler gets, with items visible and with only a
header visible. Two broken variants of the skip path fail it:
- Without the offset tracking, the items-visible case fails (delta 600
instead of 100).
- Treating the view as always having visible items, the header case
fails (delta −500 instead of 0).

**Tests run** (macOS 26.7.3, SDK 12.0.100-alpha.1.26523.103; the local
`-RepoRoot`, `-DotnetPath` and `-OutputDirectory` arguments are omitted)

```bash
dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --no-build \
  --filter "FullyQualifiedName~ItemsView|FullyQualifiedName~CarouselView|FullyQualifiedName~CollectionView|FullyQualifiedName~SwipeView"
# Passed: 96, Failed: 0

# The new tests, the existing Scrolled and threshold tests, and the temporary equivalence check (TempVisibleItemsMatchTheOriginalAlgorithm, not committed)
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -SkipXcodeVersionCheck \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests \
  -IncludeMethods ScrolledFindsTheVisibleItemsOnlyWhenSomethingUsesThem,ScrolledMeasuresDeltasFromScrollsNothingListenedTo,TempVisibleItemsMatchTheOriginalAlgorithm,ScrolledSourceChangeUsesCurrentSourceForThreshold,RemainingItemsThresholdLoadsPagesWhileScrolling
# Passed: 18, Failed: 0

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -SkipXcodeVersionCheck \
  -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CarouselViewTests,Microsoft.Maui.DeviceTests.SwipeViewTests,Microsoft.Maui.DeviceTests.CollectionViewNestedScrollingTests
# Passed: 261, Skipped: 4, Failed: 2 of 267 (host load average ~60)
```

The 2 failures in the broad run:
-
`ScrollToEndFromScrolledAsScrollToStartGoesTheRestOfTheWayReachesTheEnd`
stopped 130 pt short of the end.
- `RemainingItemsThresholdLoadsPagesWhileScrolling` hit the 15 s harness
timeout.

Both subscribe to `Scrolled` or set `RemainingItemsThreshold`, so they
take the full path, whose output is unchanged. Run on their own, they
passed 10 of 10 and 2 of 2 times. I didn't run the broad set on main
under the same load.

The temporary equivalence check compared `FirstVisibleItemIndex`,
`CenterItemIndex` and `LastVisibleItemIndex` from a `Scrolled` handler,
on every callback, with a verbatim copy of main's algorithm:
- It scrolled down and up through 9 configurations: vertical list,
3-column grid and horizontal list; grouped and ungrouped; with and
without a header taller than the viewport.
- 1,810 callbacks, 1,738 of them with visible items; 125 used the center
fallback and 4 the first/last fallback. No differences.
- `VisibleCells.Length` equaled `IndexPathsForVisibleItems.Length` on
every callback.

**Not run**

- iOS simulators or devices. The changed code is the same for iOS and
Mac Catalyst.
- The full device-test suite and UI tests.
- `dotnet format` on the whole solution: only `dotnet format whitespace`
on the changed files, which changed nothing.

Android and Windows don't use `HasScrolledObservers`. The obsolete
`Items/iOS/ItemsViewDelegator.cs` has the same pattern and is unchanged.

The benchmark (pushed for reference, not part of this PR):

```bash
S=src/Controls/tests/CollectionViewScrollBenchmark/scripts
pwsh $S/Build-ScrollBenchmark.ps1 -Variant base -Platform maccatalyst -MauiRoot <checkout of bd40bc6> -BuildTasks
pwsh $S/Build-ScrollBenchmark.ps1 -Variant fix -Platform maccatalyst -MauiRoot <checkout of this PR> -BuildTasks
pwsh $S/Invoke-ScrollBenchmark.ps1 -Variants base,fix -Platform maccatalyst -Rounds 12
pwsh $S/Compare-ScrollBenchmark.ps1 <results>.jsonl -Baseline base -Candidate fix
```

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None: this is a performance change. Related: #34153, #34240, #33719,
#40131 and #40578 changed this code, and their behavior is kept. #40881
reduces scrolling allocations on Android, measured with the same
benchmark.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it label Nov 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

MAUI Autopilot — Started

Models
  • Review: GPT-6.1 Sol (MAUI expert reviewer)
  • Fix: GPT-6.2 Sol, MAI Code 2 and Claude Opus 5.5 fix independently, then cross-examine each other; the best fix is kept
  • Test selection: GPT-6.2 Sol and MAI Code 2
Info
Label Meaning
s/autopilot-reviewing The MAUI expert reviewer is reviewing the PR
s/autopilot-fixing Fixing review findings or failing tests
s/autopilot-testing Running the relevant UI and device tests
s/autopilot-waiting-for-maintainer-review Review clean and tests passed
s/autopilot-needs-maintainer-decision The loop stopped; a maintainer decides how to continue

@github-actions github-actions Bot added the s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) label Nov 30, 2026
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

# Conflicts:
#	src/Controls/src/Core/BindableObject.cs
#	src/Controls/src/Core/Element/Element.cs
#	src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs
Copilot AI balanced review requested due to automatic review settings November 30, 2026 22:09
@kubaflo
kubaflo merged commit 0cbd57b into main Nov 30, 2026
5 of 6 checks passed
@kubaflo
kubaflo deleted the simonrozsival-scroll-allocation-reduction branch November 30, 2026 22:11

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 buffer grows without reclaiming dequeued space, making storage scale with total descendants rather than pending breadth and adding pool traffic and clearing work to the optimized path.

1 open issue

Review effort: Balanced

@kubaflo kubaflo removed s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) labels Dec 1, 2026
kubaflo added a commit that referenced this pull request Dec 1, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `187102276ebd04c1a09918a81a784bd352b78054`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Controls.Core unit suite: 8,011 passed, 0
failed.<br>↑ A three-launch BenchmarkDotNet comparison of the exact PR
parent and head shows a 3.92× improvement at 500 properties with similar
warm per-operation allocations.<br>↓ Android performance and
first-use/retained cache memory are not measured. |
| Diagnosis confidence | 8/10 | ↑ Snapshot comparison places the
regression at `0cbd57b4ce`; CPU sampling and JIT output locate the
repeated registration scan on the hot path.<br>↓ The contribution of the
extracted method versus other changes in that commit, and the larger
Android slowdown, are not independently isolated. |
| Evidence fit | 9/10 | ↑ Three independent Android runs showed the
reported attach/detach regression, increasing with the number of
dynamic-resource properties.<br>↓ The PR fix has not yet been measured
on Android. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes
directly into net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

Parent attachment refreshes an element against every key in the merged
resource dictionaries. Previously, every key caused a scan of all the
element's dynamic-resource registrations, even when the key was
unrelated. This is especially expensive for elements with many dynamic
resources.

For elements with at least eight dynamic-resource properties, cache a
lazily built ordinal set of referenced keys and skip the registration
scan for keys outside it. Newly registered keys are added to the cache;
removals may leave stale keys, which can cause an extra scan and retain
the old keys. Matching keys continue through the existing update path,
preserving resolution, specificity, and notification ordering. Before a
cache exists, elements below the threshold use the existing scan
directly.

The regression was introduced by `0cbd57b4ce` (#40881), which extracted
the per-key scan into `OnResourceKeyChanged`. A three-run snapshot
comparison found the parent of that commit at baseline speed and the
commit slower; the original Android benchmark showed a 3.4× slowdown at
500 properties. CPU sampling and JIT output identify the repeated scan
as a hot path; the exact contribution of the extraction and the larger
slowdown on Android remain unverified.

#### Benchmark: PR parent vs PR head (desktop)

[Existing BenchmarkDotNet scenario:
`ParentResourceRefreshDynamicResourceBenchmarker.AttachViews_MatchingDynamicResources_NoResourceListener`](https://github.com/dotnet/maui/blob/187102276ebd04c1a09918a81a784bd352b78054/src/Core/tests/Benchmarks/Benchmarks/ParentResourceRefreshBenchmarker.cs#L250-L290).
The same benchmark source was used for both revisions: parent
`0a5e3ae55c25536b6437b2a00a35c9389e65160c` and PR head
`187102276ebd04c1a09918a81a784bd352b78054`.

Each pair shows the measured time in milliseconds per operation:
**before** is the PR parent and **after** is the PR head. Lower is
better. The charts use different vertical scales so smaller measurements
remain visible.

```mermaid
xychart-beta
    title "Desktop: 1-20 properties"
    x-axis "Dynamic resource properties" ["1 before", "1 after", "5 before", "5 after", "20 before", "20 after"]
    y-axis "Milliseconds per operation" 0 --> 0.25
    %% Zero-height entries are positioning placeholders, not measurements.
    bar [0.0479, 0, 0.1345, 0, 0.1994, 0]
    bar [0, 0.0428, 0, 0.1296, 0, 0.0393]
```

```mermaid
xychart-beta
    title "Desktop: 100-500 properties"
    x-axis "Dynamic resource properties" ["100 before", "100 after", "500 before", "500 after"]
    y-axis "Milliseconds per operation" 0 --> 4.5
    %% Zero-height entries are positioning placeholders, not measurements.
    bar [0.7972, 0, 3.9624, 0]
    bar [0, 0.0878, 0, 1.0099]
```

| Dynamic-resource properties | Parent, ms/op (mean ± SD) | PR, ms/op
(mean ± SD) | Parent / PR |
| ---: | ---: | ---: | ---: |
| 1 | 0.0479 ± 0.0029 | 0.0428 ± 0.0023 | 1.12× |
| 5 | 0.1345 ± 0.0492 | 0.1296 ± 0.0075 | 1.04× |
| 20 | 0.1994 ± 0.0040 | 0.0393 ± 0.0020 | 5.08× |
| 100 | 0.7972 ± 0.0494 | 0.0878 ± 0.0016 | 9.08× |
| 500 | 3.9624 ± 0.1662 | 1.0099 ± 0.0245 | 3.92× |

*One operation is one view's attach and detach.* The scenario repeatedly
attaches and detaches 100 precreated views; the app has 2,000 other
resources and 500 possible dynamic-resource keys, with another 200
resources in the parent hierarchy. Each view binds to the indicated
number of those 500 keys. The non-batch benchmark uses
`OperationsPerInvoke=100`.

Measured on Apple M5 Max, macOS 26.7.3, arm64, .NET 12 SDK
`12.0.100-alpha.1.26551.101`, using BenchmarkDotNet 0.13.10 ShortRun,
out of process: three launches per parameter, three warmup and three
measured iterations per launch, 250 ms target iteration time. The table
shows BenchmarkDotNet's aggregate mean and standard deviation. Some
iterations were shorter than its recommended 100 ms and it flagged
outliers; the five-property parent result is particularly variable. The
filter is not active at 1 or 5 properties, so differences there should
not be attributed to it.

At 500 properties, the warmed allocation measurements were 56,225 B/op
on the parent and 56,230 B/op on the PR (both round to 54.91 KiB/op).
These repeated-attach measurements do **not** capture the one-time set
construction or retained cache memory, including stale keys.

<details>
<summary>Reproduce the desktop benchmark</summary>

Run from the repository root, once at each revision. The wrapper
supplies desktop-only MSBuild properties to BenchmarkDotNet's generated
restore/build projects, as on the measurement host.

```sh
root="$PWD"
wrapper="$(mktemp "${TMPDIR:-/tmp}/maui-bdn-dotnet.XXXXXX")"
results="$(mktemp -d "${TMPDIR:-/tmp}/maui-bdn-results.XXXXXX")"
cat > "$wrapper" <<'SH'
#!/bin/sh
case "$1" in
  restore|build|publish)
    exec dotnet "$@" -p:IncludeAndroidTargetFrameworks=false \
      -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false \
      -p:IncludeWindowsTargetFrameworks=false -p:IncludeTizenTargetFrameworks=false ;;
  *) exec dotnet "$@" ;;
esac
SH
chmod +x "$wrapper"
dotnet build src/Core/tests/Benchmarks/Core.Benchmarks.csproj -c Release \
  -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false \
  -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false \
  -p:IncludeTizenTargetFrameworks=false
(
  cd src/Core/tests/Benchmarks
  dotnet "$root/artifacts/bin/Core.Benchmarks/Release/net12.0/Core.Benchmarks.dll" \
    --filter '*ParentResourceRefreshDynamicResourceBenchmarker.AttachViews_MatchingDynamicResources_NoResourceListener' \
    --job Short --launchCount 3 --iterationTime 250 --cli "$wrapper" \
    --exporters json --artifacts "$results"
)
printf 'Benchmark results: %s\n' "$results"
rm "$wrapper"
```

</details>

#### Original Android regression (not a measurement of this fix)

Pixel 10, API 37, arm64, CoreCLR; BenchmarkDotNet ShortRun, three
independent processes per revision with three warmup and three measured
iterations each. Values are the medians of the independent launch means.
**The PR fix has not been run on this device.**

Each pair shows the measured time in milliseconds per operation:
**before** is earlier main and **after** is regressed main, not the PR
fix. Lower is better. The charts use different vertical scales so
smaller measurements remain visible.

```mermaid
xychart-beta
    title "Android regression: 1-20 properties"
    x-axis "Dynamic resource properties" ["1 before", "1 after", "5 before", "5 after", "20 before", "20 after"]
    y-axis "Milliseconds per operation" 0 --> 0.9
    %% Zero-height entries are positioning placeholders, not measurements.
    bar [0.125, 0, 0.161, 0, 0.309, 0]
    bar [0, 0.125, 0, 0.263, 0, 0.786]
```

```mermaid
xychart-beta
    title "Android regression: 100-500 properties"
    x-axis "Dynamic resource properties" ["100 before", "100 after", "500 before", "500 after"]
    y-axis "Milliseconds per operation" 0 --> 20
    %% Zero-height entries are positioning placeholders, not measurements.
    bar [1.117, 0, 5.628, 0]
    bar [0, 3.580, 0, 19.129]
```

| Dynamic-resource properties | Earlier main `1da0f535b5`, ms/op |
Regressed main `c008cbff6b`, ms/op | Regressed / earlier |
| ---: | ---: | ---: | ---: |
| 1 | 0.125 | 0.125 | 1.00× |
| 5 | 0.161 | 0.263 | 1.63× |
| 20 | 0.309 | 0.786 | 2.55× |
| 100 | 1.117 | 3.580 | 3.20× |
| 500 | 5.628 | 19.129 | 3.40× |

At 500 properties, allocations in this original Android comparison fell
from 216,138 to 56,265 B/op. These are measurements of the two
historical snapshots, not the PR fix.

#### Other validation

- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--no-build -nologo -p:IncludeAndroidTargetFrameworks=false
-p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeWindowsTargetFrameworks=false
-p:IncludeTizenTargetFrameworks=false` — passed: 8,011 passed, 0 failed,
30 skipped.
- An earlier local stopwatch harness (not committed) measured a
pre-final prototype at 500 properties at 1.0–1.2 ms/op versus 3.9–4.8
ms/op for the historical head; the BenchmarkDotNet comparison above
measures the actual PR head.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No linked issue; the regression was identified in the parent-resource
attach benchmark.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-controls-collectionview CollectionView, CarouselView, IndicatorView platform/android

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants