Repository navigation
perf(unhead): reduce resolver allocations - #838
Conversation
Nuxt-style servers call createHead() per request, and the default init entry (htmlAttrs lang, charset, viewport) was re-normalized through normalizeEntryToTags + weight/dedupe assignment on every request since the entry tag cache is per instance. Hoist the default init object to module scope and lazily normalize it once, mirroring the resolveTags first-resolve path exactly. The shared array is attached as entry._precomputedTags and only used when nothing can observe or alter normalization: - default capoTagWeight (no tagWeight option, no per-resolve override) - no custom propResolvers (the entry has no on* handlers so the built-in server resolver is a no-op) - no entries:normalize or entries:resolve hooks at resolve time - no entry options - disableDefaults and user init entries keep the normalize path The array is never cached on entry._tags so entries:resolve listeners can never reach the shared array, and tag-mutating hooks are already covered by the existing needsClone defensive copy.
Add an internal _static marker to PropResolver for resolvers that are the identity function for plain non-reactive JSON values. VueResolver (pure isRef/toValue unwrap) and the built-in server on* resolver are marked, and the attach-time guard now only requires every custom propResolver to be static instead of requiring none, so @unhead/vue (Nuxt-style per-request createHead) gets the precomputed default init entry too. Resolve-time guards are unchanged.
* perf(unhead): reduce per-resolve allocations in resolveTags Per-resolve fast paths in the tag resolver, gated on registered hooks: - only snapshot `head.entries` into an array when an `entries:resolve` listener will see it; the `_pending` sweep and entry loop iterate the map directly otherwise - allocate hook context objects (`entries:resolve`, `entries:normalize`) lazily behind listener checks instead of before every callHook - drop the intermediate `entryTags: HeadTag[][]`; entry tags are pushed straight into the resolve context and defensively cloned in place only when a tag-mutating hook is registered (scan still runs after the entry loop so mid-resolve registrations are honored) - remove the dead `_nonMutating` check (read but never set anywhere) - reuse the pre-dedupe tags array in valuesToTags and compact in place in sanitizeTags instead of allocating fresh output arrays A listener returning a promise on the synchronous pipeline is now surfaced with a one-time console.warn naming the hook (previously silently dropped, with later listeners deferred past the render): - PromisesPlugin no longer returns its (never-awaited) promise, so it can't defer later-registered `entries:resolve` listeners - schema-org's `tags:resolve` listener was needlessly async (no awaits); making it sync also removes per-render promise machinery (-22% CPU on the cached schema.org render bench) * fix(unhead): keep sanitizeTags contract, snapshot entries when loop hooks exist Review follow-ups for the resolver allocation work: - `sanitizeTags` is public API (`unhead/utils`): restore its returns-a-new-array contract. The in-place compaction moves to a module-private `sanitizeTagsInPlace` used by `resolveTags`; the export delegates via a copy. Export snapshots unchanged. - iterating the live entries Map let an `entries:normalize` listener that calls `head.push()` feed the new entry back into the same resolve (a per-entry push would loop forever). Snapshot the entries whenever `entries:resolve` OR `entries:normalize` listeners exist; the live Map is only iterated when no user hook code can run inside the loop. propResolvers / tagWeight do not force the snapshot: they are pure value transforms and calling head.push from them is out of contract. - regression test: an entry pushed by an entries:normalize listener must defer to the next resolve (passes on base, fails on the previous commit, passes now)
The warn-once flag for async listeners on the sync hook pipeline was module state, violating the CONTRIBUTING module-state policy (input originates from user hook behavior, not module constants). Move it to the head instance so each head (e.g. each SSR request's) warns independently and test runs can't bleed state into each other.
This reverts commit 93725e8.
This reverts commit 9a59b6f.
📝 WalkthroughWalkthrough
ChangesTag resolution flow
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
bench/resolve-tags.bench.ts (1)
2-2: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider replacing the deprecated
renderSSRHeadAPI.As per the provided code snippets from
packages/unhead/src/server/renderSSRHead.ts,renderSSRHeadis deprecated in favor ofhead.render(). Consider updating the benchmark to use the newer API, unless the legacy synchronous wrapper is intentionally being used to isolate CPU/memory allocations without introducingPromiseoverhead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@bench/resolve-tags.bench.ts` at line 2, Replace the deprecated renderSSRHead usage in the benchmark with the newer head.render() API, updating the surrounding benchmark flow to handle its return value as needed. If this benchmark intentionally measures the legacy synchronous wrapper without Promise overhead, retain renderSSRHead and document that intentional exception.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@bench/resolve-tags.bench.ts`:
- Line 2: Replace the deprecated renderSSRHead usage in the benchmark with the
newer head.render() API, updating the surrounding benchmark flow to handle its
return value as needed. If this benchmark intentionally measures the legacy
synchronous wrapper without Promise overhead, retain renderSSRHead and document
that intentional exception.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 2b37f15a-c29a-47ed-97bc-79251fae0f2e
📒 Files selected for processing (3)
bench/resolve-tags.bench.tspackages/unhead/src/utils/resolve.tspackages/unhead/test/unit/hooks/entries-normalize-push.test.ts
…ion-fast-paths-split # Conflicts: # packages/unhead/src/utils/resolve.ts
Keep the spread fast path for normal entry tag arrays and use indexed copying above a safe argument-count threshold. This avoids a RangeError for large cached entries without slowing the common path.\n\nUpdate the resolver benchmark to use head.render() and cover cached renders.
📦 Bundle Size
All bundles (14)
⚡ Performance (directional)🟢 2 faster
All benchmarks (14)
Baseline: main @ 1d8b0e1 · 2026-07-19 · gzipped is the headline size metric · perf is directional (shared-runner, gated) |
Avoid constructing the entries:resolve context when only entries:normalize listeners require the entry snapshot. Add FlatMetaPlugin first and cached render cases to the resolver benchmark.
Drop the unrealistic 32k-tag spread fallback, reducing the bundle cost while retaining the allocation fast path. Mark async stream heap deltas informational because repeated unchanged runs are bimodal due to ReadableStream cleanup.
🔗 Linked issue
Related to #828
❓ Type of change
📚 Description
Builds on #828, which is now in
main.resolveTagsstill created an entry snapshot, hook contexts, an intermediate tag matrix, and fresh compaction arrays on every render when no relevant hooks were registered.This PR creates those structures only when listeners need them and reuses owned arrays through dedupe and sanitization. Cached entry normalization is invalidated when the active
entries:resolveandentries:normalizelistener count changes.Client and streaming heads now use the same private adapter and decorate one core head object. The previous streaming wrapper copied the core, so its renderer could not see hooks attached to the wrapper. Push, patch, dispose,
onRendered, auto-render, and hydration locking now share one lifecycle implementation.The allocation benchmark uses 40 ordinary head entries and
head.render(). The 32k-tag case is only a regression guard for large cached arrays; it is not the source of the reported allocation win.📊 Benchmarks
GitHub same-runner, built-dist comparison against
main:CPU and wall-clock results remain within noise. Streaming allocation is also within noise. The bundle matrix adds 1.2 kB gzip in aggregate; each consumed bundle grows by 88 B to about 0.1 kB (0.9% to 2.1%).
✅ Verification
pnpm lintpnpm typecheckpnpm buildpnpm test:import-inert