Repository navigation
Avoid boxing allocations - #12677
Avoid boxing allocations#12677
Conversation
97a85e9 to
2657648
Compare
2657648 to
3fcb516
Compare
f91167d to
653ae85
Compare
|
This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or it will be closed in 10 days. |
|
@Youssef1313 what is needed to merge this one please? I think it is worth un-stale, but need to know how to finalize |
|
@MartinZikmund Conflicts need to be resolved, as well as this comment: #12677 And if there is any build errors to get green. There were no major blockers for this one, I think. |
|
This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or it will be closed in 10 days. |
|
This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or it will be closed in 10 days. |
|
@ebariche can this be finalized and merged? |
|
This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or it will be closed in 10 days. |
Mechanical rename of BoolBoxes.BoxedTrue/BoxedFalse to BoolBoxes.True/False across Uno.UI, the regenerated WinAppSDK stubs, the generators, the boxing code fix, their tests and the DependencyProperty rule. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01UuyxCj3yRMnaT3RYDrgZfJ Co-Authored-By: Youssef Victor <[email protected]>
The cached box classes become top-level types in the Uno.UI.Helpers.Boxes namespace, and the Box overloads move to Boxer, so call sites read BoolBoxes.False and Boxer.Box(value) instead of Boxes.BoolBoxes.False and Boxes.Box(value). The generators and the WinAppSDK stubs emit the new names, and the DependencyProperty generator and the code fix now resolve Boxer to decide whether the boxes are accessible. All of it is internal to Uno.UI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01UuyxCj3yRMnaT3RYDrgZfJ Co-Authored-By: Youssef Victor <[email protected]>
The MinuteIncrement changed callback unboxed e.OldValue and e.NewValue only to box them again for OnMinuteIncrementChanged(object, object). Passing the event-argument objects through removes both allocations for every value, including the common 5/15/30 increments that have no cached box. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01UuyxCj3yRMnaT3RYDrgZfJ Co-Authored-By: Youssef Victor <[email protected]>
Aligns the int family with BoolBoxes and DoubleBoxes, which follow the C# keyword names. Mechanical rename across Uno.UI, the regenerated WinAppSDK stubs, the DependencyProperty and WinAppSDK sync generators, the boxing code fix, their tests and the DependencyProperty rule. The boxes are internal, so there is no public API impact. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01G49thtH4UbuSE3jbKvQQvv Co-Authored-By: Youssef Victor <[email protected]>
The GetTargetIndexFromNavigationAction stub took (object o, int i) where WinUI's ModernCollectionBasePanel takes (BOOLEAN allowWrap, UINT itemIndexHintForHeaderNavigation), so CalendarView had to pass a cached box for allowWrap. With the real parameter types it passes a plain false and nothing is boxed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01G49thtH4UbuSE3jbKvQQvv Co-Authored-By: Youssef Victor <[email protected]>
RichTextBlock, RichTextBlockOverflow, Block and TextRangeAdapter landed on master after this branch forked and tripped UnoInternal0002. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
5895a26 to
9c1093c
Compare
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-12677/wasm-skia-net9/index.html |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-12677/docs/index.html |
|
The build 235916 found UI Test snapshots differences: Details
|
|
Tick the box to add this pull request to the merge queue (same as
|
UnoInternal0002 flagged every cached-box candidate, so the sweep also rewrote string formatting, tracing and automation code. Only report boxes that flow into the property system: arguments of calls taking a DependencyProperty or building PropertyMetadata, and results of DP callbacks (coercion, PropMethodCall, per-property lookups). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
GetDefaultValue2(DependencyProperty, out object) returns the default through its out parameter, which the DP scope missed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
With the analyzer scoped to DP values, drop the boxes the sweep added to formatting, exceptions, tracing and automation code, where they only added noise. Keep them where the path is hot and the value is cached: binding FastConvert, the ancestors cache, CornerRadiusFilterConverter and the ListViewBase remove path. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
ContainerFromIndex boxed the index for every materialized container it compared against. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LhNTQL2AUCVUSLN6c7AhDA
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-12677/wasm-skia-net9/index.html |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-12677/docs/index.html |
|
The build 235941 found UI Test snapshots differences: Details
|
|
This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again. |
GitHub Issue: closes #12410
PR Type:
✨ Feature
What changed? 🚀
SetValue,FrameworkPropertyMetadataand the property store all takeobject, so everybool,intanddoublethat reaches them is boxed — on every property set, and once per registration for every primitive default. This PR
makes the framework hand out cached boxes for the common values instead, keeps the DependencyProperty value path that
way with an analyzer at
error, and emits the cached boxes from the source generators.At a glance (full numbers and method under Benchmarks):
bool, or a cachedint/doublevalue, is 24–48 bytes lighter per set; re-setting aboolto its current value no longer allocates at all.Uno.UItypes initialize (837 fewer boxes), and −73 KB (−0.2%) from process start to an idle first page.ListViewscroll steps 2.4 MB less.Uno.UI.Helpers.BoxesThe cached boxes live in the
Uno.UI.Helpers.Boxesnamespace; everything isinternaltoUno.UI.BoolBoxes(True/False),IntBoxes(NegativeOne/Zero/One),DoubleBoxes(Zero/One),NullableDoubleBoxes,VerticalAlignmentBoxes,StretchBoxes,RoutedEventFlagBoxes.Boxer.Box(...)has overloads forbool,int,double,VerticalAlignment,StretchandRoutedEventFlag.doubleis matched by bit pattern, so-0.0and NaN payloads keep their own box.1.0is cached because it is the default ofOpacity,ScaleXandScaleY.RoutedEventFlagcaches each of its 37 declared members; combinations fall through and box.VerticalAlignmentBoxes,StretchBoxesandNullableDoubleBoxesdeclared their fields with value types, so reading one asobjectre-boxed and the caches never cached anything —DependencyProperty.GetDefaultValueallocated on every call forStretch.Fill.Uno.UI.Helpers.Boxesclass:Boxes.BooleanBoxes.BoxedFalseis nowBoolBoxes.False, andBoxes.Box(value)isBoxer.Box(value).DependencyObject.SetValue(DependencyProperty, bool)DependencyObjectgains aninternalbooloverload — onlybool. This resolves the review thread that blocked this PR(
discussion_r1249338772): typed overloads are dangerous because implicit numeric conversions routebyte/short/charinto an
intoverload andfloat/longinto adoubleone, storing the wrong boxed type and throwingInvalidCastExceptionon the way out. C# has no built-in implicit conversion tobool, so that overload cannot capturea numeric argument by accident;
intanddoubleuseBoxer.Box(...)at the call site instead.Analyzer and code fix
BoxingDiagnosticAnalyzer(inUno.UI.SourceGenerators.Internal), both diagnostics aterrorforUno.UI:UnoInternal0002— a boxing conversion toobjectfor which a cached box exists, on the DependencyProperty value path only:DependencyProperty(SetValue,SetCurrentValue, ...) or constructs aPropertyMetadata;object-returning function that takes aDependencyObject,DependencyPropertyorDependencyPropertyValuePrecedences(coercion,PropMethodCall, per-property lookups), or assigned to theoutvalue of one (GetDefaultValue2).UnoInternal0003— an argument reaching a typedSetValue(DependencyProperty, T)overload through an implicit conversion (numeric widening or a user-defined conversion), which would store the wrong boxed type. The value argument is matched by parameter, so reordered named arguments are handled.It deliberately does not report:
errorthere only added noise to ported code;object, and constants with no cached box (-0.0,2.0, aRoutedEventFlagcombination).Framework types are matched by namespace and name, so look-alikes from other namespaces are ignored.
BoxingCodeFixProviderrewrites implicit boxing and explicit(object)casts, keeping inner conversions:(object)(int)bbecomesBoxer.Box((int)b).Generators
DependencyPropertyGenerator,DependencyPropertyMixinGeneratorand the WinAppSDK sync generator emit the cached boxes for generated setters andDefaultValue/FrameworkPropertyMetadatadefaults; the 60 affectedsrc/Uno.UI/Generated/**stubs are regenerated (boxing substitutions only).Uno.UI.Helpers.Boxes.Boxeris accessible from the compilation, so any other consumer of[GeneratedDependencyProperty]keeps compiling.DefaultValue = -0.0dnow registers negative zero. Previously the generator emitted(double)-0— integer negation — which registered positive zero.Call sites
354
Boxer.Box(...)calls and 480 cached-box references across 201 hand-writtenUno.UIfiles (plus the regenerated stubs). They cover every site the analyzer fires on, plus a few hand-picked hot paths outside the DP scope where the value is usually cached: bindingFastConvert(string →bool/int/double, which then lands in a DP), theDependencyObjectancestors cache (bool),CornerRadiusFilterConverter(often0.0) and theListViewBaseindex repair on remove (-1).ItemsControl.ContainerFromIndexno longer boxes the index per container it compares against..claude/rules/dependency-properties.mdnow points contributors at the cached boxes instead ofdefault(T).Benchmarks 📊
Method
masterat this PR's merge base (d70012ce06) vs this PR (b5a968bff2), built from the same tree inReleaseinto a headless Skia console app (UseHeadless(), Fluent resources merged). The runner verifies before every pass that only the PR build containsBoxer.GC.GetAllocatedBytesForCurrentThread, which is exact: 17 of the 25 steady-state rows and 3 of the 4 UI-thread startup measurements read the same byte count in every launch. Bold deltas are identical in every launch or have non-overlapping master/PR ranges; the rest carry a p-value.QueryThreadCycleTime), plus wall-clock. Both are compared with a two-sided Mann-Whitney U test.Startup
OnLaunched²new XamlControlsResources()WindowListView, to idleUno.UItypes¹ Varies slightly between launches; p is a two-sided Mann-Whitney U over 15 launches per arm.
² The headless host runs the UI thread on a different thread than
Main, so these two phases use process-wide counters (all threads) and are noisier.Per operation (detached
Border)IsHitTestVisibletoggledIsHitTestVisible = true(unchanged value)Opacitytoggled 1.0 ↔ 0.0Canvas.SetLeft(el, 0.0)Canvas.SetLeft(el, 1.0)Canvas.SetZIndex(el, 0)Canvas.SetLeft(el, i)— uncached (control)Canvas.SetZIndex(el, i)— uncached (control)Canvas.GetLeft(el)(control)new Border()new Grid()new TextBlock()new Button()new CheckBox()Uncached values are unchanged by design: they fall outside the cached set and still box. Construction is unchanged because boxed defaults are paid once per registration, not per instance.
Realistic workloads (live tree, per iteration)
Gridof 50Borders (size,Opacity, hit-test,Canvas.Left/ZIndex)IsHitTestVisible+Opacityon 50 elements, lay outIsEnabledon 30 Fluent controls (Disabled/Normal states), lay outGoToStatePointerOver ↔ Normal on 30 Fluent controlsTextBoxesCheckBox.IsChecked+ 10ToggleSwitch.IsOnRequestedThemeLight ↔ Dark on a 40-control pageListView(2,000 items) scroll step¹ Not identical across launches, and the difference is not statistically significant (p = 0.21, n = 5 per arm), so no claim is made for this row.
Gen0 collections over the 2,000-step scroll were 30 on both.
CPU time and startup time
No workload shows a statistically significant CPU-time or wall-clock difference. The smallest p-value across all 31 rows is 0.06, and
new Button()— identical code and identical allocations in both builds — swung +230% between arms. That is the noise floor of a hybrid-core laptop, and it is larger than the time cost of the 24-byte allocations removed here. Some medians lean faster on the PR (type initialization −9%, 2,000 scroll steps −15%), but none is significant, so none is claimed.Validation
Uno.UIbuilds with 0 errors and 0UnoInternal0002/UnoInternal0003diagnostics in Debug and Release, with analyzers on. Re-checked in Debug after the analyzer was narrowed; the boxing analyzer, code-fix and DependencyProperty generator tests pass (58/58).DefaultValueoutput and a-0.0default keeping its sign. New analyzer and code-fix tests runUnoInternal0002/UnoInternal0003and the code action end to end: the DP scope (SetValue-family andPropertyMetadataarguments, coercion/PropMethodCallresults,outdefaults) and what stays outside it (string.Format,AppendFormat, arrays, unrelated lambdas), implicit and explicit boxing, inner conversions, string concatenation forms, reordered namedSetValuearguments,RoutedEventFlagcombinations and look-alike types from other namespaces. Each regression test added in review was run failing before its fix.b5a968bff2(the benchmarked commit) after re-running two stages that failed for reasons unrelated to this PR. One was the Android agent's 45-minute timeout; the other wasWhen_TextBox_Has_ContextFlyout_Keyboard_Trigger_Shows_Flyouton tvOS, which is already excluded as flaky on Skia iOS and WASM. The only later commit,d4dc8a642b, passesTimePicker's already-boxed values through instead of re-boxing them.PR Checklist ✅
erroris the standing regression guard.Screenshots Compare Test Runresults. — the reported diffs (57 Linux / 2310 Windows / 11 WASM) are not from this change: every PR built since 2026-09-10 reports exactly 57 Linux and 2310 Windows (e.g. test: Disable five flaky runtime tests (InputPane occlusion, scroll chaining, BitmapIcon monochrome) #24491, chore: Update to .NET 11 rc.1 #24492, docs: Close out the 7.0 documentation and reconciliation leftovers #24351, fix(wasm): Keep the hidden TextBox input off-screen on iOS #24527), because the comparer matches PNGs by exact SHA1 against recentmasterbuilds.Other information
masterin 2026. A literal rebase was not possible (three years of drift;DependencyObjectGenerator,Uno.UWPSyncGenerator,Uno.UI.TestsandUno.UI.Skia.csprojwere gone or moved), so the change was replayed semantically and the call sites were re-found on today's code by the analyzer. The original commits are ate7f610c8c71.bool-only subset of the DependencyProperty generator change; itsDependencyPropertyMixinGeneratorhunk is carried here.