Repository navigation
perf(startup): defer a11y, charting, and logger init off the cold path - #179
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
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 touchingCharting.D3Chartsfrom the host render loop unless charting is active. - Make host/logger plumbing “lazy by default” by allowing
ILoggerto be null and using null-conditional logging throughout host/reconciler paths; introduceReactorApp.AppLoggeras a process-wide fallback. - Update
startup_perfharness TFMs and the benchmark script output path tonet10.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
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>
Chris Anderson (codemonkeychris)
force-pushed
the
perf/lazy-startup
branch
from
May 7, 2026 01:51
215b7f1 to
43ad04b
Compare
- 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>
This was referenced Jun 25, 2026
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
XamlAppLoaded(median, ms)WindowLoaded(median, ms)Numbers are medians of 5 runs of
tests/startup_perf/run_startup_bench.ps1, run-1 cache-cold runs excluded per the methodology intests/startup_perf/README.md.What changed
ReactorHostno longer constructsAccessibilitySettings+UISettingsin its ctor. Both move to a new internalEnsureChartingActive()called the first time a chart element is created (wired viaChartingActivationfromD3Charts's cctor and the chart implicit-conversion operators). Apps without charts skip the WinRT activations entirely.D3Chartsthread-static push —Render()no longer referencesCharting.D3Charts. The three thread-static writes live in a separatePushChartingStatemethod that stays JIT-cold until the first chart mounts, eliminating theD3Chartsstatic-cctor cascade for chart-free apps.RequestRenderskips the dispatcher hop on the very first render when called on the UI thread (theMount()-from-OnLaunchedpath). Saves one dispatcher tick and matches what an imperative WinUI3 app does. Subsequent setStates keep the existing dispatcher-batch behavior so coalescing still works._loggerfields are nullable and default to null; all_logger.LogXxxcalls are now null-conditional inReactorHost,ReactorHostControl, and the threeReconcilerpartials. NewReactorApp.AppLoggerstatic lets devtools (or any caller) populate a process-wide fallback so every host picks it up automatically without forcing apps to wire upMicrosoft.Extensions.Logging.Notes
tests/startup_perf/Blank{Reactor,WinUI3}.csprojbumped tonet10.0-windows10.0.22621.0to restore against the current Reactor TFM (Reactor moved to net10 in 76d0075).run_startup_bench.ps1updated to look in the matching output dir.ReactorApplication.xamlloads<XamlControlsResources/>unconditionally;BlankWinUI3has noApp.xaml. That's a separate, larger discussion.Test plan
dotnet build tests/startup_perf/BlankReactor/BlankReactor.csproj -c Releasesucceeds.tests/startup_perf/run_startup_bench.ps1 -Runs 5 -Skip RNWproduces medians in line with the table above.samples/Charting) still picks up forced-colors / reduced-motion correctly.🤖 Generated with Claude Code