Skip to content

perf: reduce framework hydration allocations - #479

Merged
Mohamed Mansour (mohamedmansour) merged 1 commit into
microsoft:mainfrom
mohamedmansour:mohamedmansour-reduce-resolver-allocations
Aug 25, 2026
Merged

perf: reduce framework hydration allocations#479
Mohamed Mansour (mohamedmansour) merged 1 commit into
microsoft:mainfrom
mohamedmansour:mohamedmansour-reduce-resolver-allocations

Conversation

@mohamedmansour

Copy link
Copy Markdown
Contributor

Summary

  • allocate the condition resolver only for components that evaluate a runtime condition
  • share the existing empty-array sentinel for absent text, attribute, condition, and repeat metadata in both client wiring and SSR hydration
  • clear populated binding arrays in place while guarding the shared empty sentinel

Performance

Measured in Chromium with the direct streaming-browser-bench lazy-hydration matrix at 10, 100, and 1,000 elements. Each arm ran 60 samples in counterbalanced baseline → branch → branch → baseline order with forced-GC CDP heap samples. Both source trees included the same PR #475 runtime fix and differed only in template-element.ts.

Mode Elements Baseline retained heap Branch retained heap Delta
eager 10 214.3 KiB 214.5 KiB noise (+0.1%)
eager 100 335.5 KiB 326.8 KiB -2.6%
eager 1,000 1,378.0 KiB 1,244.6 KiB -9.7% (-133.4 KiB)
lazy-hydrate 1,000 635.1 KiB 588.1 KiB -7.4% (-47.0 KiB)
lazy-render 1,000 652.0 KiB 605.3 KiB -7.2% (-46.7 KiB)

A separate object-identity probe confirmed exactly four avoided allocations per element: one resolver closure and three empty binding arrays, or 40 / 400 / 4,000 allocations at 10 / 100 / 1,000 elements. Baseline roots retained N resolver functions and 3N unique empty arrays; the branch retained no resolver on condition-free roots and reused one pre-existing empty sentinel.

End-to-end custom-element definition medians remained effectively flat:

  • eager 1,000: 26.95 ms → 27.25 ms (+0.30 ms)
  • lazy-hydrate 1,000: 21.70 ms → 21.75 ms (+0.05 ms)
  • lazy-render 1,000: 21.45 ms → 21.55 ms (+0.10 ms)

Bundle size changes by +83 B gzip for eager and +100 B gzip for lazy modes. Exact body.innerHTML SHA-256 values matched between baseline and branch at all three scales.

Validation

  • pnpm --dir packages/webui-framework test:unit
  • focused Playwright fixtures: 82 passed, 2 skipped
  • cargo xtask check

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

Copilot-Session: 701fdb47-fef7-4cf9-b17f-ed54b1c113dc

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 reduces per-element allocations during WebUI framework hydration/wiring by avoiding unnecessary resolver closure creation and by reusing a shared empty-array sentinel for binding arrays when a template block has no bindings of a given kind.

Changes:

  • Added a bindingArray() helper to reuse EMPTY_ARR for zero-length binding collections while still allocating mutable arrays when bindings exist.
  • Deferred allocating the condition resolver closure until the first runtime condition evaluation via $conditionResolver().
  • Avoided unnecessary .length = 0 writes during instance teardown by clearing binding arrays only when they’re non-empty.

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@mohamedmansour
Mohamed Mansour (mohamedmansour) merged commit d8601ca into microsoft:main Aug 25, 2026
24 checks passed
@mohamedmansour
Mohamed Mansour (mohamedmansour) deleted the mohamedmansour-reduce-resolver-allocations branch August 25, 2026 04:21
Mohamed Mansour (mohamedmansour) added a commit that referenced this pull request Aug 25, 2026
## Summary

Empty scriptless templates were still paying for `TemplateElement`'s
per-instance state despite having no DOM, bindings, events, CSS, or
lifecycle work. This adds a narrow minimal-host fast path while leaving
every behavior-bearing or CSS-bearing template on the existing full host
path.

- use a prototype-only `HTMLElement` host only when metadata and the
registered style closure prove there is no work
- preserve delayed parent `:` writes through the existing pending-state
store
- exclude stateless static opt-outs from retained streaming update
targets
- keep CSS-bearing empty templates on `TemplateElement`, avoiding
duplicate style lifecycle code

The simplification reduced the PR from 454 to 304 added lines and
removed the extra pending-state module.

## Performance

Measured against `d8601ca0` (including #479 and #480) in Chrome
151.0.7922.174. Each row uses 24 empty compiler-owned tags, 2 warmups,
and 12 interleaved fresh-realm runs per arm. Incremental heap is sampled
with forced GC immediately before and after definition/upgrade.

| Hosts | JS heap (main -> PR) | JS reduction | JS saved/host | Combined
saved/host | Install P50 (main -> PR) | Install reduction |
|---:|---:|---:|---:|---:|---:|---:|
| 5,000 | 905,240 B -> 117,428 B | 87.03% | 157.56 B | 288.85 B | 17.00
-> 5.80 ms | 65.88% |
| 15,000 | 2,194,146 B -> 274,864 B | 87.47% | 127.95 B | 257.05 B |
44.45 -> 16.15 ms | 63.67% |
| 30,000 | 4,129,812 B -> 517,516 B | 87.47% | 120.41 B | 248.97 B |
93.45 -> 32.55 ms | 65.17% |

Per-instance framework-owned properties fall from 14 to 0 for hosts with
no queued writes.

Compared with the earlier implementation in this PR, the simplified
branch uses another 3-12% less incremental JS heap and installs 14-18%
faster. A prior run on `e971c13a` was discarded after #479 landed.

## Correctness

- parent properties queued before definition are applied on connection
or streaming activation; newer post-definition writes win
- hosts without queued writes remain zero-field; only actual queued keys
become own properties
- CSS-bearing empty templates retain the existing `TemplateElement`
style path
- templates with HTML, bindings, blocks, events, state roots, Shadow
DOM, or CSS remain on `TemplateElement`
- state-capable dormant hosts remain streaming update targets; minimal
hosts without `setState` do not
- ordinary authored `data-ws` remains untouched outside streaming mode

## Validation

- `pnpm --dir packages/webui-framework test:unit` - 328 passed
- focused static-host, template-element, styles, and streaming pipeline
tests - 140 passed
- `cargo xtask check` - all checks passed

---------

Copilot-Session: 4533723c-3962-4d08-946c-3c373b653eec
Mohamed Mansour (mohamedmansour) added a commit that referenced this pull request Aug 26, 2026
## Release

Bumps WebUI to `0.0.26`.

Previous release tag: `v0.0.25`

## Changes since `v0.0.25`

Features:

- Python hosts now have an official typed PyO3 renderer package with
buffered, partial, template, token, and host-driven streaming APIs
(feat: add official Python renderer package #453 by @mohamedmansour).
- Progressive SSR can place transport-flushed streaming boundaries
inside reusable components while preserving component ownership and
continuation state (feat: support component-local streaming boundaries
#460 by @mohamedmansour).
- Components can defer compiler-owned hydration until interaction, with
router preload handoff and a combined lazy-render policy (feat: add
compiler-driven interaction hydration #485 by @mohamedmansour).
- Builds can opt into global Light DOM CSS while preserving explicit
authored Shadow roots and deterministic style closures (feat: make Light
DOM a global CSS opt-in #429 by @mohamedmansour).
- State projection supports application-owned TypeScript 7.0.2 while
retaining the TypeScript 6 migration path (feat: support TypeScript 7
projection compilation #452 by @mohamedmansour).
- WebUI Press supports layout-scoped compile-time named regions with
fallback HTML, state, components, and scripts (feat(press): add
compile-time named regions #484 by @mohamedmansour).
- FAST v2 and v3 gain plugin-owned local and npm component discovery
with validated FAST template transformation (feat: add plugin-owned FAST
component discovery #378 by @janechu).

Fixes:

- Missing condition identifiers are treated as falsy before negation and
logical evaluation, aligning SSR with the browser runtime (fix: negate
missing condition paths correctly #449 by @mohamedmansour).
- FAST route state now scales through escaped scalar kebab-case
attributes shared by FAST v2 and v3 (fix: scale FAST route state with
scalar attributes #450 by @janechu).
- Dynamic Link-mode components wait for native stylesheet readiness
across navigation and component assets, preventing unstyled flashes
(fix: prevent dynamic component stylesheet flashes #454 by
@mohamedmansour).
- Authored component definitions defer whenever compiled template
metadata has not arrived, including ordinary router navigation (fix:
defer authored define() whenever template metadata is missing #461 by
@mohamedmansour).
- Client structural updates preserve authored order and sibling
ownership for shared slots and raw HTML ranges (fix: preserve source
order for shared structural slots #465 by @mohamedmansour, fix: preserve
siblings around raw HTML updates #466 by @mohamedmansour).
- Native-element attributes no longer leak into the local state of a
later component (perf(handler): stop native attributes leaking into
component state #469 by @mohamedmansour).
- Templates-and-state-only SSR bootstrap payloads no longer require
component style metadata (fix: allow SSR bootstrap without component
styles #475 by @mohamedmansour).
- The high-level Rust `serve_request` path now preserves complete render
options, including CSP nonces, while sharing the same entry and request
path with partial rendering (fix: forward CSP nonces through
serve_request #488 by @mohamedmansour).
- Projection compilation bounds source reads, excludes binary and
unsupported-loader inputs from semantic analysis, and preserves
deterministic cleanup under large esbuild graphs (fix: bound projection
adapter source reads #489 by @mohamedmansour).
- Router pending UI remains mounted through pre-commit work and settles
at the synchronous DOM commit, with stale, aborted, and re-entrant
navigation cleanup kept generation-safe (fix: settle router pending UI
during navigation commits #491 by @mohamedmansour).

Docs:

- The documentation site adds accessible responsive navigation, improved
reading layouts, stronger search behavior, and Playground recovery
states (feat: polish WebUI documentation experience #459 by
@mohamedmansour).
- Slot-resolution implementation guidance now documents pre-order
lookup, pending placement ownership, and marker handling (chore: clarify
slot resolution comments #471 by @mohamedmansour).
- Repeated `w-ref` behavior is now explicit: refs are scalar and the
last wired occurrence wins, while stable authored IDs or item components
provide identity-based lookup (chore: clarify repeated w-ref behavior
#490 by @mohamedmansour).

Maintenance:

- Release and package policy metadata now constrains the transitive h2
advisory, uses SPDX NuGet licensing, and classifies publishing jobs
correctly (chore: allow constrained h2 advisory #451 by @janechu, fix:
use modern NuGet license metadata #457 by @janechu, chore: mark
publishing jobs as release jobs #458 by @janechu).
- The development and CI Rust toolchain is updated to 1.98 with the
resulting warnings resolved (Update rust toolchain version and fix
clippy warning #462 by @telecos).
- Release builds use Thin LTO to retain cross-crate optimization with
faster linking (perf: switch release builds to Thin LTO #464 by
@mohamedmansour).
- Handler and expression hot paths reduce attribute vtable calls, render
lookup and scope allocations, and single-term condition overhead
(perf(handler): centralize HTML attribute writing in ResponseWriter #467
by @mohamedmansour, perf(expressions): fast-path single-term conditions
#470 by @mohamedmansour, perf(handler): reduce render lookup and scope
allocations #472 by @mohamedmansour).
- Node rendering can reuse immutable prepared-state snapshots and
bounded per-route output capacity hints (perf(node): reuse prepared
state across renders #477 by @mohamedmansour, perf: reuse Node render
output capacity #478 by @mohamedmansour).
- Framework hydration releases bootstrap data sooner and reduces
allocations for bindings, empty hosts, and visible conditionals (perf:
reduce framework hydration allocations #479 by @mohamedmansour, perf:
release SSR bootstrap memory after hydration #480 by @mohamedmansour,
perf: reduce empty template host overhead #482 by @mohamedmansour, perf:
remove visible conditional anchors #483 by @mohamedmansour).
- Benchmark tooling now renders the full contact workload, runs
Criterion baselines per target, and restores the streaming hydration
fixture (fix(bench): render contacts in contact-book benchmark #468 by
@mohamedmansour, fix(xtask): run Criterion benchmarks per target #473 by
@mohamedmansour, fix: repair streaming hydration benchmark fixture #476
by @mohamedmansour).

## Validation

- `cargo xtask check`

---------

Co-authored-by: Copilot App <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.

3 participants