Skip to content

perf(startup): defer a11y, charting, and logger init off the cold path - #179

Merged
Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
perf/lazy-startup
May 7, 2026
Merged

Chris Anderson (codemonkeychris) merged 2 commits into
mainfrom
perf/lazy-startup

Conversation

@codemonkeychris

Copy link
Copy Markdown
Collaborator

Summary

Reactor's empty-window startup overhead vs a vanilla WinUI3 baseline drops from ~163 ms to ~89 ms on ARM64 — about 74 ms (~45%) of the structural gap closed by deferring four pieces of work that the typical app never uses.

WinUI3 Reactor (before) Reactor (after) Δ
XamlAppLoaded (median, ms) 71.9 234.8 161.2 −73.6
WindowLoaded (median, ms) 124.6 257.8 183.1 −74.7
TTFP (median, ms) 171.1 294.8 223.1 −71.7

Numbers are medians of 5 runs of tests/startup_perf/run_startup_bench.ps1, run-1 cache-cold runs excluded per the methodology in tests/startup_perf/README.md.

What changed

  • Lazy a11y / UISettings — ReactorHost no longer constructs AccessibilitySettings + UISettings in its ctor. Both move to a new internal EnsureChartingActive() called the first time a chart element is created (wired via ChartingActivation from D3Charts's cctor and the chart implicit-conversion operators). Apps without charts skip the WinRT activations entirely.
  • Lazy D3Charts thread-static push — Render() no longer references Charting.D3Charts. The three thread-static writes live in a separate PushChartingState method that stays JIT-cold until the first chart mounts, eliminating the D3Charts static-cctor cascade for chart-free apps.
  • Sync first render — RequestRender skips the dispatcher hop on the very first render when called on the UI thread (the Mount()-from-OnLaunched path). Saves one dispatcher tick and matches what an imperative WinUI3 app does. Subsequent setStates keep the existing dispatcher-batch behavior so coalescing still works.
  • Lazy logging — _logger fields are nullable and default to null; all _logger.LogXxx calls are now null-conditional in ReactorHost, ReactorHostControl, and the three Reconciler partials. New ReactorApp.AppLogger static lets devtools (or any caller) populate a process-wide fallback so every host picks it up automatically without forcing apps to wire up Microsoft.Extensions.Logging.

Notes

  • tests/startup_perf/Blank{Reactor,WinUI3}.csproj bumped to net10.0-windows10.0.22621.0 to restore against the current Reactor TFM (Reactor moved to net10 in 76d0075). run_startup_bench.ps1 updated to look in the matching output dir.
  • The remaining ~89 ms gap to BlankWinUI3 is structural: ReactorApplication.xaml loads <XamlControlsResources/> unconditionally; BlankWinUI3 has no App.xaml. That's a separate, larger discussion.

Test plan

  • dotnet build tests/startup_perf/BlankReactor/BlankReactor.csproj -c Release succeeds.
  • tests/startup_perf/run_startup_bench.ps1 -Runs 5 -Skip RNW produces medians in line with the table above.
  • CI: existing unit + selftest suites pass (no behavior changes for chart-using apps; lazy paths exercised by any chart selftest).
  • Spot-check: a chart-using sample (e.g. samples/Charting) still picks up forced-colors / reduced-motion correctly.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR targets cold-start performance by moving rarely-used work (charting/a11y initialization and logging) off the default startup path, and by avoiding an unnecessary dispatcher hop on the very first render. It also updates the startup perf harness projects/scripts to match the repo’s current net10 TFM.

Changes:

  • Defer charting-related a11y (AccessibilitySettings, UISettings) initialization until the first chart is used, and avoid touching Charting.D3Charts from the host render loop unless charting is active.
  • Make host/logger plumbing “lazy by default” by allowing ILogger to be null and using null-conditional logging throughout host/reconciler paths; introduce ReactorApp.AppLogger as a process-wide fallback.
  • Update startup_perf harness TFMs and the benchmark script output path to net10.0-windows10.0.22621.0.
Show a summary per file
File Description
tests/startup_perf/run_startup_bench.ps1 Updates perf harness output path TFM to net10.
tests/startup_perf/BlankWinUI3/BlankWinUI3.csproj Bumps benchmark app TFM to net10.
tests/startup_perf/BlankReactor/BlankReactor.csproj Bumps benchmark app TFM to net10.
src/Reactor/Hosting/ReactorHostControl.cs Makes logger nullable and uses ReactorApp.AppLogger fallback + null-conditional logging.
src/Reactor/Hosting/ReactorHost.cs Defers charting/a11y init, adds first-render synchronous path, and makes logging nullable.
src/Reactor/Hosting/ReactorApp.cs Adds process-wide AppLogger and routes unhandled exception logging through it.
src/Reactor/Hosting/ChartingActivation.cs Adds indirection for charts to request host charting activation.
src/Reactor/Core/Reconciler.Update.cs Switches reconciler logging to null-conditional.
src/Reactor/Core/Reconciler.Mount.cs Switches mount-time logging to null-conditional.
src/Reactor/Core/Reconciler.cs Allows nullable logger and updates logging call sites accordingly.
src/Reactor/Charting/D3Charts.cs Adds static ctor to request charting activation on first use.
src/Reactor/Charting/Charts.Tree.cs Requests charting activation from chart implicit conversions.
src/Reactor/Charting/Charts.cs Requests charting activation from chart implicit conversions.

Copilot's findings

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 13/13 changed files
  • Comments generated: 2

Comment thread src/Reactor/Hosting/ReactorHost.cs Resolved
Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Reactor's empty-window startup (XamlAppLoaded median) drops from ~234 ms
to ~161 ms on ARM64 — about 74 ms (~45%) of the structural gap vs the
BlankWinUI3 baseline. Four lazy-init changes; nothing on the cold path
allocates or loads anything an app without charts / without a logger
will use.

- ReactorHost no longer constructs AccessibilitySettings + UISettings
  in its ctor. Both move to a new EnsureChartingActive() called the
  first time a chart element is created (via ChartingActivation, hooked
  from D3Charts cctor + chart implicit operators). Apps without charts
  pay zero WinRT activation tax.

- Render() no longer references Charting.D3Charts unconditionally. The
  three thread-static writes live in PushChartingState, JIT-cold until
  the first chart mounts — this stops the D3Charts cctor cascade for
  chart-free apps.

- First render runs synchronously when Mount() is called on the UI
  thread (the common path from OnLaunched), saving one dispatcher tick
  and matching what an imperative WinUI3 app does. Subsequent setStates
  keep the existing dispatcher-batch behavior so coalescing still works.

- ILogger fields are nullable, default to null, and all .LogXxx call
  sites are null-conditional. ReactorApp.AppLogger is the new public
  static that devtools (or any caller) can populate to give every host
  a logger without forcing apps to wire up Microsoft.Extensions.Logging.

Bench projects bumped to net10.0-windows so they restore against the
current Reactor TFM; run_startup_bench.ps1 picks up the new path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- EnsureChartingActive: gate the 0→1 transition with
  Interlocked.CompareExchange, and marshal the WinRT-touching init body
  onto the dispatcher thread when called from a background thread.
  Concurrent chart-element creation can no longer double-subscribe
  HighContrastChanged / ColorValuesChanged or write the [ThreadStatic]
  D3Charts flags from a non-UI thread.
- Render(): use Volatile.Read on the activation flag so the UI thread
  observes the cross-thread Interlocked write.
- Drop the misleading "devtools populates AppLogger" wording — no such
  assignment exists today. Comments now describe actual behavior:
  hosts snapshot AppLogger at ctor time, so callers must set it before
  constructing their first host.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@codemonkeychris
Chris Anderson (codemonkeychris) merged commit 939d7ab into main May 7, 2026
9 of 10 checks passed
@codemonkeychris
Chris Anderson (codemonkeychris) deleted the perf/lazy-startup branch May 7, 2026 03:15
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 30, 2026
…omics (#660)

Remove per-frame delegate/closure allocations and full-barrier atomics from the
render-loop hosts (ReactorHost + ReactorHostControl), which run at render/data-tick
frequency on the data-grid stress workload:

  #178 QueryCache.DispatcherPost: pass action.Invoke, drop the () => action() trampoline
  #179 cache _rerenderAction instead of () => RequestRender() every render
  #180 cache _renderLoopHandler (DispatcherQueueHandler) for TryEnqueue
  #181 cache _requestRenderAction (RequestRender method group) for BeginRender + Reconcile
  #182 HotReloadService.ConsumeUpdatePending: Volatile.Read fast-path, atomic only when pending
  #183 AnimationAmbient.HasAny sentinel gates the per-setState AsyncLocal walk
  #185 _lastRenderMs: Volatile.Write (single writer) instead of Interlocked.Exchange
  #186 report gate: integer ElapsedMilliseconds compare instead of Elapsed.TotalSeconds
  #187 remove unconditional [embed:trace] Console.Error writes at window open

Behavior preserved: identical render cadence, delegate semantics, and re-render
coalescing; HasAny is a one-way sentinel so any app that opens an Animations.Animate
transaction keeps the full AsyncLocal path. New AnimationAmbient.HasAny tests.

Deferred (flagged to coordinator): theme resolution cache (#85/#86) — #85's per-element
theme-name cache needs generation invalidation on localized RequestedTheme application
which lives in Reconciler.cs (sibling-owned), so it's a cross-boundary change; and theme
resolution can't be measured headlessly. #184 charting dirty-gate (chart-specific, secondary).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 30, 2026
…rame atomics, cache theme-brush resolution (#660) (#751)

* perf(render-loop): cache per-frame host delegates + drop per-frame atomics (#660)

Remove per-frame delegate/closure allocations and full-barrier atomics from the
render-loop hosts (ReactorHost + ReactorHostControl), which run at render/data-tick
frequency on the data-grid stress workload:

  #178 QueryCache.DispatcherPost: pass action.Invoke, drop the () => action() trampoline
  #179 cache _rerenderAction instead of () => RequestRender() every render
  #180 cache _renderLoopHandler (DispatcherQueueHandler) for TryEnqueue
  #181 cache _requestRenderAction (RequestRender method group) for BeginRender + Reconcile
  #182 HotReloadService.ConsumeUpdatePending: Volatile.Read fast-path, atomic only when pending
  #183 AnimationAmbient.HasAny sentinel gates the per-setState AsyncLocal walk
  #185 _lastRenderMs: Volatile.Write (single writer) instead of Interlocked.Exchange
  #186 report gate: integer ElapsedMilliseconds compare instead of Elapsed.TotalSeconds
  #187 remove unconditional [embed:trace] Console.Error writes at window open

Behavior preserved: identical render cadence, delegate semantics, and re-render
coalescing; HasAny is a one-way sentinel so any app that opens an Animations.Animate
transaction keeps the full AsyncLocal path. New AnimationAmbient.HasAny tests.

Deferred (flagged to coordinator): theme resolution cache (#85/#86) — #85's per-element
theme-name cache needs generation invalidation on localized RequestedTheme application
which lives in Reconciler.cs (sibling-owned), so it's a cross-boundary change; and theme
resolution can't be measured headlessly. #184 charting dirty-gate (chart-specific, secondary).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* perf(theme): cache (key,theme) -> Brush resolution, cleared on theme change (#660 #86)

ThemeRef.Resolve recursed Application.Resources.MergedDictionaries (XamlControlsResources
and its nested dictionaries) on every resolve — per cell x per color token x per render on
the data-grid workload. Cache the deterministic (resourceKey, themeName) -> Brush result in
a process-wide ConcurrentDictionary and clear it from the hosts' theme-change handlers
(ActualThemeChanged + UISettings.ColorValuesChanged). Transient-null Application.Resources
(early startup) is not cached, so no poisoned null entry. Cached value mirrors the uncached
return exactly (including null for unknown keys); ThemeDictionary brushes are shared
instances, so returning the cached reference is identical behavior.

Self-contained in Theme.cs (no BrushHelper/ThemeBinding/Reconciler coupling). The per-element
theme-NAME cache (#85) is intentionally NOT here — it needs a generation bump where a localized
RequestedTheme is applied (Reconciler.cs, sibling-owned), which is a cross-ownership change
flagged to the coordinator.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(theme): complete #86 brush-cache invalidation per #751 review

Two correctness hardenings on the (key,theme)->Brush cache:

1. Wire ReactorHostControl to UISettings.ColorValuesChanged (high-contrast /
   accent / palette) -> InvalidateResolutionCache, mirroring ReactorHost. Before,
   the embedded host only invalidated on ActualThemeChanged (Light/Dark), so an
   app using ReactorHostControl without a ReactorApp would keep stale brushes on a
   same-theme accent/high-contrast change. Subscribe on theme-listener attach,
   unsubscribe in Dispose.

2. Cache ONLY successful (non-null) resolutions. A cached null for an unknown key
   would go stale if a ResourceDictionary defining that key is merged in after the
   first resolve (a dictionary add raises no theme-change event). Unknown keys are
   rare; re-walking them is the same cost as pre-cache and always correct.

Invalidation now covers: Light<->Dark (ActualThemeChanged, both hosts — AND the
cache key includes the theme name so a toggle auto-misses) + accent/palette/
high-contrast (ColorValuesChanged, both hosts). Existing theme selftests pass with
the cache active, incl. StructuralSkip_ThemeRangeParity
(ThemeRange_ForegroundReresolvedOnToggle: resolve brush -> toggle theme -> assert
re-resolved) and Issue522_CacheClear_StyleClearedDespiteCacheClear. Full headless
suite 9915/0; build 0/0.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* test(theme): regression coverage for #86 brush-cache invalidation (H1/H2)

Selftest fixtures pinning the two converged review findings (the code fixes
landed in 3fd38c4):

- Theme_BrushCacheNullMissNotCached (H2): resolve an unknown key → null (NOT
  cached) → merge a ResourceDictionary defining it → resolves to the brush. Guards
  against the cached-null poisoning a later-merged key (XamlIslandBootstrap /
  docking-embed late XamlControlsResources binding).
- Theme_BrushCacheInvalidationReResolves (H1 mechanism): resolve key→brushA
  (cached) → swap to brushB for the same (key,theme) → still brushA (stale) →
  ThemeRef.InvalidateResolutionCache() (what the hosts call on
  ColorValuesChanged/ActualThemeChanged) → re-resolves to brushB.

Both green. Validates the invalidation path the ReactorHostControl
ColorValuesChanged wiring (3fd38c4) depends on.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants