Skip to content

[Perf] Eliminate value-type boxing in BindableObject.SetValue #34080

Open

Description

@simonrozsival

Summary

BindableObject.SetValue is the central code path for all property updates in .NET MAUI — layout, styles, bindings, handler propagation. The current implementation is fully object-based, which boxes every value type on every call. We instrumented the property system with runtime diagnostics and measured that 65% of all property sets are value types — meaning the majority of SetValue calls pay for unnecessary boxing allocations.

Problem — measured on a real app

We instrumented SetterSpecificityList<T> and BindablePropertyContext to track every property set in a representative Sandbox app on Mac Catalyst (~75 visual elements: CollectionView with 30 data-templated items, form controls, 4 resource styles, bindings with deliberate Style+Binding overlap). Key findings from a single page load:

65% of all property sets (2,198 / 3,386) store a value type (Boolean, Single, Color, Double, Point, Thickness, etc.) into SetterSpecificityList<object> — boxing on every write, unboxing on every read and comparison.

Setter specificity Total sets Value type sets VT % Key boxed types
FromHandler 1,154 1,136 98% Boolean (1,104), Double (28)
Style 213 213 100% Color (78), Double (40), Thickness (38)
ManualValueSetter 1,827 753 41% Single (306), Point (153), Double (81)
FromBinding 192 96 50% Color (64), Double (32)
Total 3,386 2,198 65%

Notable findings:

  • Handler propagation is almost pure boxing: IsEnabled and InputTransparent cascade bool through the visual tree — 1,104 box allocations per screen load (24 bytes each).
  • Style application is 100% value types: every Setter.Value for Color, Double, Thickness, FontAttributes gets boxed. Zero reference types flow through styles.
  • 83% of Bindings lists (2,825 / 3,386) are allocated but never used — every BindablePropertyContext eagerly creates a SetterSpecificityList<BindingBase> even though most properties never have a binding.

SetterSpecificityList entry count distribution

We also tracked how many entries each SetterSpecificityList instance actually holds at peak. Out of 6,450 tracked instances:

Max entry count Instances Percent What this means
0 3,741 58.0% Allocated but never written to (includes 2,825 unused Bindings lists)
1 96 1.5% Single entry — only DefaultValue or a single setter
2 2,565 39.8% Two entries — the typical case: DefaultValue + one setter (Style/Handler/Manual)
3 48 0.7% Three entries — Style + Binding overlap (e.g., FontSize set by both a Style and a Binding)

99.3% of instances have ≤2 entries. The max count ever observed is 3 — never 4 or higher. This means:

  • Inline _top + _second fields cover 99.3% of cases without any array allocation
  • The _rest overflow array is allocated in <1% of cases and never holds more than 1 element
  • The current implementation uses parallel sorted arrays with binary search — far more complex than needed for collections that almost never exceed 2 items

Root cause

SetterSpecificityList<T> has a where T : class constraint. This forces all value types to be stored as SetterSpecificityList<object>, boxing on write, unboxing on read. This single constraint blocks the entire typed pipeline.

Where boxing happens

Each SetValue call for a value type hits:

  1. Boxing on entry — double → object
  2. Unboxing for comparison — Equals(object, object) must unbox both values
  3. Unnecessary TryConvert — value.GetType() + type comparison, even when types already match
  4. Coerce delegate — receives boxed value, unboxes, potentially re-boxes
  5. SetterSpecificityList<object> — stores all values as object
  6. PropertyChanged/PropertyChanging callbacks — receive boxed arguments

Proposal

A series of internal refactors (no public API changes) delivered as incremental PRs (4 total, down from 5 — lazy Bindings init is subsumed by making SetterSpecificityList<T> a struct):

PR 1: Refactor SetterSpecificityList to a value type

Remove the where T : class constraint and change SetterSpecificityList<T> from a class to a struct. Replace the current parallel-array + binary-search implementation with a _top/_second/_rest inline design:

struct SetterSpecificityList<T>
{
    Entry _top;       // highest-priority entry (always inline)
    Entry _second;    // second-highest (always inline)
    RestList? _rest;  // overflow — allocated only for 3+ entries (<1% of cases)
    int _count;

    struct Entry { T Value; SetterSpecificity Specificity; }
}

This design is directly motivated by the measured entry count distribution above:

  • 99.3% of instances need at most 2 entries → zero array allocations for the common case
  • The 0.7% with 3 entries allocate a single-element overflow array
  • No binary search needed — with ≤2 inline entries, comparison is a simple if/else

Making it a struct means SetterSpecificityList<T> is embedded inline in BindablePropertyContext — no separate heap allocation per list. This eliminates thousands of small GC-tracked objects at startup. The Bindings list that was previously eagerly allocated as a separate object (unused 83% of the time) becomes a zero-cost inline field — it occupies ~48 bytes in the context but requires no separate allocation and no GC tracking.

We benchmarked struct vs class SetterSpecificityList in isolation (Apple M1 Max, .NET 10.0.1, BenchmarkDotNet):

Scenario Class (current) Struct (proposed) Improvement
Create 100 contexts, set 2 entries each 2,220 ns / 9,600 B 758 ns / 7,200 B 2.9× faster, 25% less memory
Create 100 contexts, set 3 entries each 5,219 ns / 21,600 B 4,036 ns / 19,200 B 1.3× faster, 11% less memory
Allocate 1000 empty contexts 14,228 ns / 96,000 B 5,093 ns / 72,000 B 2.8× faster, 25% less memory
Update existing value 1000× 509 ns / 64 B 551 ns / 72 B ~equal (within noise)

We also benchmarked a ConditionalWeakTable-based approach to eliminate the _rest pointer entirely, but the hash-table overhead made the 3-entry path 16× slower (65 μs vs 4 μs). Keeping _rest as an inline nullable field is the right tradeoff — 8 bytes well spent.

Same API surface, drop-in replacement, independently faster for reference types too.

PR 2: Add typed pipeline

Layer internal typed primitives:

  1. BindableProperty<T> — internal subclass with typed delegates and IEqualityComparer<T>
  2. BindablePropertyContext<T> — typed storage with SetterSpecificityList<T>
  3. SetValueCore<T> / SetValueActual<T> — typed fast path, no boxing
  4. GetValue<T> — typed read, no unboxing

PR 3: Convert hot-path properties

Convert X, Y, Width, Height, IsEnabled, IsVisible, Opacity etc. to BindableProperty<T> internally.

PR 4: TypedBinding fast path

When TypedBinding<TSource, TProperty> targets a BindableProperty<TProperty> with no Converter/StringFormat, route directly to SetValueCore<T>.

Compatibility

  • All existing object-based APIs preserved — no breaking changes
  • Typed path used only when type information matches at runtime (property is BindableProperty<T>)
  • Falls back to existing untyped path otherwise

Benchmark results (prototype)

All benchmarks run on Apple M1 Max, .NET 10.0.1, BenchmarkDotNet.

What Before After Improvement
SetValue<double> throughput (1000×) 26.5 μs 15.6 μs 41% faster
SetValue<double> allocations (1000×) 24,000 B 0 B 100% eliminated
Layout 4 props × 100 elements 11.7 μs 6.6 μs 43% faster
Layout allocations 9,600 B 0 B 100% eliminated
SetterSpecificityList creation 25.9 ns 6.0 ns 4.3× faster
SetterSpecificityList memory/property 184 B 64 B 65% less
TypedBinding push baseline 1.35× 35% faster, 0 B alloc

Back-of-the-napkin startup estimate

Using a startup trace from dotnet new maui -sc: MAUI property-system work is ~494 ms of ~5,995 ms main-thread startup. Applying measured gains (~35–43%) to that bucket suggests roughly 170–210 ms startup savings (~3–3.5% total). Conservative and directional — exact savings depend on app composition.

Related issues

Diagnostics methodology

Full details are in our experiment report (on the set-value-perf-improvements branch, file SetValue-Primitives-Experiment-Proposal.md). The instrumentation code and Sandbox app modifications are also on that branch for reproducibility.

Activity

  1. changed the title [-][Perf] Eliminate value-type boxing in BindableObject.SetValue codepath[/-] [+][Perf] Eliminate value-type boxing in BindableObject.SetValue[/+] on Feb 17, 2026
  2. added
    perf/startup-time
    on Feb 17, 2026
  3. added 2 commits that reference this issue on Feb 20, 2026
  4. StephaneDelcroix commented on Feb 28, 2026

    @StephaneDelcroix
    Contributor

    Review Notes & Blind Spots

    After reading through the spec, a few things stand out:

    1. Struct mutation hazard (HIGH RISK)

    Field writes like context.Values[specificity] = value require careful struct-in-struct semantics. Any accidental copy means the mutation is silently lost. All mutation sites in BindableObject need to use ref access patterns consistently. This needs a thorough audit — it's the most likely source of subtle regressions.

    2. Default value representation for value types

    Without where T : class, how do you distinguish "no entry" from "entry with value 0.0" (the default for double)? The Entry struct likely needs a sentinel (e.g., bool hasValue), which increases its size. Not addressed in the spec.

    3. RestList design is vague

    What is RestList? — array, linked list? How does it handle >3 entries? "Max 3 observed" is empirical on one app, not a contract. If it grows dynamically, it reintroduces allocation. If it's capped, that's a silent failure for pathological cases. Needs a clear design decision.

    4. PR 1 doesn't eliminate boxing end-to-end

    Removing where T : class unblocks the typed plumbing, but SetValue(BindableProperty, object) still takes object at the call site. All callers still box value types. PR 1 optimizes internal storage, not entry points. Boxing stays until PR 2 + PR 4 land. Worth being explicit about this so expectations are set — PR 1 alone won't show up in allocation profiles.

    5. Linear scan vs binary search

    With ≤2 inline entries, linear scan wins easily. But the 3-entry overflow path (rare as it is) is asserted to be rare, not proven to be faster than the old binary search. Minor, but worth a benchmark.

    6. Boxing for known value types — source generation approach

    For common value types (int, float, double, bool, Color, Thickness, etc.), we could have the framework emit typed BindableProperty<T> variants alongside the existing object ones. A switch on known value types would generate the generic BP automatically. Framework properties would have both object and typed variants; the router picks typed when available.

    XamlSourceGenerator integration: If a generic BindableProperty<T> exists, XSG should extract the type information from it and emit typed SetValue<T> calls instead of object variants. Runtime inflation and XamlC should remain unchanged — only XSG leverages the type info at codegen time.

  5. jonathanpeppers commented on Mar 3, 2026

    @jonathanpeppers
    Member

    I saw this issue as well:

    I think everything makes sense -- the only thing we might consider is when we do the first prototype:

    • "copilot change every BindableProperty to BindableProperty"
    • do a Release build of MAUI + sample app
    • what is the app size change?

    I think it will increase, but hopefully a small amount and would be worth it. 👍

  6. added a commit that references this issue on Mar 11, 2026
  7. added a commit that references this issue on Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    perf/startup-time

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions