Skip to content

Commit 0f14430

Browse files
ryansolidClaude via Cursorcursoragent
authored
perf(signals): narrow store writes clone by spread; overlay only for wide owned backings (#3367)
Part one of #3360. Per write+commit on a one-key store: rc.7 629 ns -> 340 ns steady state; a fresh store's first write+commit 3x cheaper (the reporter's 100k-store shape ~265 -> ~90 ms). - cloneRaw spreads plain-data containers (Object.prototype, every own key an enumerable data property) instead of the descriptor walk: same result, ~1/50th the cost. The one-time accessor scan grades the container (sc 0/1/2) and records its own-key count (kc, bumped by set-trap writes of new keys so a record that grows from {} still graduates). - The #3044 prototype overlay is taken only for WIDE (>32 keys) containers over an OWNED backing. Narrow ones clone cheaper than they overlay (Object.create turns the backing into a V8 prototype and every flatten writes into that prototype); an unowned backing had to be privatize-cloned at commit anyway, so the overlay there paid create + clone + per-key copy. - Grade-2 containers flatten and take overlay first-writes by bare assignment; a non-plain defineProperty through the draft downgrades the grade so descriptor-bearing keys keep the descriptor paths. The remaining per-write cost is the weak-collection registration of each pending backing (~190 ns); that is part two. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent c0299bf commit 0f14430

7 files changed

Lines changed: 313 additions & 22 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/signals": patch
3+
---
4+
5+
Store writes on narrow containers are ~1.85× cheaper (629 → 340 ns per write+commit steady state; a fresh store's first write+commit 3× cheaper). Plain-data containers now clone by spread instead of a descriptor walk, and the #3044 prototype overlay is taken only for wide (>32 own keys) containers over an already-owned backing — for narrow or unowned ones the overlay cost more than the clone it was meant to avoid (`Object.create` turns the backing into a V8 prototype, and the first commit had to privatize-clone anyway). Part one of #3360; the remaining per-write cost is the weak-collection registration of each pending backing.

‎packages/signals/src/store/next/store.ts‎

Lines changed: 69 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ function TargetShape(this: any) {
130130
this.d = undefined;
131131
this.a = undefined;
132132
this.sc = undefined;
133+
this.kc = undefined;
133134
this.nc = undefined;
134135
this.ab = undefined;
135136
this.fam = undefined;
@@ -169,7 +170,8 @@ function createTarget(
169170
t.px = null;
170171
t.d = false;
171172
t.a = false;
172-
t.sc = false;
173+
t.sc = 0;
174+
t.kc = 0;
173175
t.nc = 0;
174176
t.ab = null;
175177
t.fam = fam;
@@ -419,6 +421,15 @@ const foldOlds = new Map<StoreNextTarget, Record<PropertyKey, any>>();
419421
let hookInstalled = false;
420422

421423
function cloneRaw(source: Record<PropertyKey, any>, t?: StoreNextTarget): Record<PropertyKey, any> {
424+
// Plain-data fast path (#3360): a scanned `Object.prototype` container
425+
// whose own keys are all enumerable data clones by spread — the same
426+
// result as the descriptor walk below (own enumerable string+symbol keys,
427+
// normalized writable+configurable), at ~1/50th the cost. Callers always
428+
// pass their own committed backing as `source`.
429+
if (t) {
430+
t.sc || scanAccessorsOnce(t);
431+
if (t.sc === 2) return { ...source };
432+
}
422433
// Descriptor-preserving shallow clone (R29: installed getters stay live;
423434
// ruled 2026-08-17: frozen sources clone unfrozen — theirs stays frozen).
424435
// Data descriptors normalize to writable+configurable (the clone is OURS to
@@ -450,20 +461,35 @@ function copyOwn(to: object, from: object, key: PropertyKey): void {
450461
}
451462

452463
/** One-time own-accessor scan (Annex-B probes, no descriptor allocation);
453-
* returns true when the container is plain data (overlay-safe). */
464+
* returns true when the container is plain data (overlay-safe). Also grades
465+
* the container for the plain-data fast paths (`sc` = 2): `Object.prototype`
466+
* and every own key an enumerable data property — what a spread copies
467+
* exactly and what a bare assignment lands exactly. */
454468
function scanAccessorsOnce(target: StoreNextTarget): boolean {
455469
const src = target.v;
456-
for (const key of Reflect.ownKeys(src)) {
470+
const keys = Reflect.ownKeys(src);
471+
let plain = Object.getPrototypeOf(src) === Object.prototype;
472+
for (const key of keys) {
457473
// Own keys shadow prototype accessors, so the lookups are exact here.
458474
if (lookupGetter.call(src, key) !== undefined || lookupSetter.call(src, key) !== undefined) {
459475
target.a = true;
476+
plain = false;
460477
break;
461478
}
479+
if (plain && !propertyIsEnumerable.call(src, key)) plain = false;
462480
}
463-
target.sc = true;
481+
target.sc = plain ? 2 : 1;
482+
target.kc = keys.length;
464483
return !target.a;
465484
}
466485

486+
/** Own-key count above which a draft opens as a prototype overlay rather
487+
* than a clone (#3360). Below it a spread clone of a plain container is
488+
* cheaper than the overlay's `Object.create` (V8 converts the committed
489+
* backing into a prototype, and every later flatten writes into that
490+
* prototype); above it the clone's O(keys) copy dominates (#3044). */
491+
const OVERLAY_MIN_KEYS = 32;
492+
467493
/** Downgrade a prototype-overlay pending backing to the clone path: builds
468494
* the real container (committed + overlay writes − deletes) that fold will
469495
* SWAP in as the committed backing, exactly as if the draft had started on
@@ -522,15 +548,26 @@ function ensurePB(target: StoreNextTarget): Record<PropertyKey, any> {
522548
// backings (the committed layer is another store's proxy — an overlay
523549
// would route every read-through into its traps), accessor containers
524550
// (live getters).
551+
// The overlay pays off only for a WIDE container over an OWNED committed
552+
// backing (#3360). Narrow containers clone cheaper than they overlay (a
553+
// spread is a fast-path copy; `Object.create` turns the backing into a
554+
// V8 prototype and every later flatten writes into that prototype). An
555+
// unowned backing has to be privatized (cloned) at commit anyway, so an
556+
// overlay there would cost the create PLUS the clone PLUS a per-key
557+
// copy — the clone path does the one clone and swaps it in. The first
558+
// write on a fresh store is exactly that case.
559+
const v = target.v;
525560
if (
526561
!target.fam?.opt &&
527562
!target.ch &&
528-
!Array.isArray(target.v) &&
529-
(target.sc ? !target.a : scanAccessorsOnce(target))
563+
!Array.isArray(v) &&
564+
(target.sc !== 0 ? !target.a : scanAccessorsOnce(target)) &&
565+
target.kc > OVERLAY_MIN_KEYS &&
566+
ownedRaw.has(v)
530567
) {
531-
pb = target.pb = Object.create(target.v) as Record<PropertyKey, any>;
568+
pb = target.pb = Object.create(v) as Record<PropertyKey, any>;
532569
target.ovl = true;
533-
} else pb = target.pb = cloneRaw(target.v, target);
570+
} else pb = target.pb = cloneRaw(v, target);
534571
// Optimistic families: seed USER drafts from the OPTIMISTIC VIEW
535572
// (committed + active node overrides), so follow-up writes compose on
536573
// optimism instead of clobbering from base (#2951's compose half).
@@ -639,7 +676,7 @@ export function adoptPB(
639676
// draft rescans once (#3044 audit follow-up).
640677
target.ovl = false;
641678
target.del = null;
642-
target.sc = false;
679+
target.sc = 0;
643680
target.a = false;
644681
target.wk = null; // adoption supersedes staged trap writes
645682
target.v = incoming;
@@ -763,7 +800,12 @@ function parentSlotKey(target: StoreNextTarget, expected: unknown): PropertyKey
763800
function flattenOverlay(t: StoreNextTarget, pb: Record<PropertyKey, any>): void {
764801
privatizeCommitted(t);
765802
const v = t.v;
766-
for (const key of Reflect.ownKeys(pb)) copyOwn(v, pb, key);
803+
// Plain-data grade (sc 2): every own key on the overlay is an enumerable
804+
// writable data slot (set-trap writes; a non-plain defineProperty
805+
// downgrades the grade) — a bare assignment lands it without the
806+
// descriptor round trip.
807+
for (const key of Reflect.ownKeys(pb))
808+
t.sc === 2 ? ((v as any)[key] = pb[key as any]) : copyOwn(v, pb, key);
767809
if (t.del !== null) {
768810
for (const key of t.del) delete (v as any)[key];
769811
t.del = null;
@@ -1504,6 +1546,7 @@ const hasOwn = Object.prototype.hasOwnProperty;
15041546
// shadow prototype accessors, so hasOwn + lookup is an exact own-check.
15051547
const lookupGetter = (Object.prototype as any).__lookupGetter__;
15061548
const lookupSetter = (Object.prototype as any).__lookupSetter__;
1549+
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
15071550
function isOwnAccessor(src: Record<PropertyKey, any>, key: PropertyKey): boolean {
15081551
return (
15091552
hasOwn.call(src, key) &&
@@ -1984,7 +2027,14 @@ const traps: ProxyHandler<StoreNextTarget> = {
19842027
wk.add(key);
19852028
wk.add("length");
19862029
}
1987-
} else if (target.wk !== WK_ALL) (target.wk ??= new Set()).add(key);
2030+
} else {
2031+
if (target.wk !== WK_ALL) (target.wk ??= new Set()).add(key);
2032+
// Live own-key estimate for the overlay/clone choice (#3360): `in`
2033+
// sees through an overlay to the committed keys, so this counts keys
2034+
// NEW to the container. Deletes are not un-counted (a stale high
2035+
// count only picks the overlay a little early).
2036+
if (!(key in pb)) target.kc++;
2037+
}
19882038
// Own data keys literally named "prototype"/"constructor" land as data —
19892039
// defineProperty sidesteps a proto-chain setter named the same.
19902040
if (UNSAFE_KEYS.has(key)) {
@@ -1999,8 +2049,10 @@ const traps: ProxyHandler<StoreNextTarget> = {
19992049
}
20002050
// Overlay first-write DEFINES the own key: assignment through the proto
20012051
// chain would reject on a non-writable committed property (the clone
2002-
// path normalized descriptors for exactly this — R51 parity).
2003-
if (target.ovl && !hasOwn.call(pb, key)) {
2052+
// path normalized descriptors for exactly this — R51 parity). A
2053+
// plain-data-graded backing (sc 2, owned: every slot writable) takes the
2054+
// bare assignment — it lands as an own key on the overlay all the same.
2055+
if (target.ovl && target.sc !== 2 && !hasOwn.call(pb, key)) {
20042056
Object.defineProperty(pb, key, {
20052057
value: uv,
20062058
writable: true,
@@ -2027,6 +2079,10 @@ const traps: ProxyHandler<StoreNextTarget> = {
20272079
// Unwrap before ensurePB (see the set trap: self-reference materializes).
20282080
if ("value" in desc) desc = { ...desc, value: unwrapValue(desc.value) };
20292081
const pb = ensurePB(target);
2082+
// A non-default data descriptor (or an accessor) leaves the plain-data
2083+
// grade: the key reaches the committed backing as defined, so the spread
2084+
// clone and bare-assignment paths no longer describe it.
2085+
if (target.a || !(desc.enumerable && desc.writable && desc.configurable)) target.sc = 1;
20302086
pendingNotify.add(target);
20312087
if (target.wk !== WK_ALL) (target.wk ??= new Set()).add(key);
20322088
Object.defineProperty(pb, key, desc);

‎packages/signals/src/store/next/target.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,17 @@ export interface StoreNextTarget {
9999
* this target (first-read scan, defineProperty, or clone scan). Gates the
100100
* fold diff's descriptor-safe path and the get trap's descriptor path. */
101101
a: boolean;
102-
/** Accessor scan performed (scan-once on first trap read; adopted data is
103-
* not rescanned — legacy-parity behavior). */
104-
sc: boolean;
102+
/** Accessor scan grade: 0 = not yet scanned (adoption resets — adopted data
103+
* is not rescanned until the next draft), 1 = scanned, 2 = scanned and
104+
* PLAIN DATA — `Object.prototype` with every own key an enumerable data
105+
* property. Grade 2 unlocks the spread clone (cloneRaw), bare-assignment
106+
* overlay writes and flatten (#3360); a non-plain defineProperty through
107+
* the draft downgrades it to 1. */
108+
sc: 0 | 1 | 2;
109+
/** Own-key count: exact at scan, then bumped by set-trap writes of keys new
110+
* to the container (never decremented — an estimate for the overlay/clone
111+
* choice only, #3360). */
112+
kc: number;
105113
/** Adoption diff base, non-null when the backing was swapped by adoption
106114
* this batch: the view the nodes were LAST TOLD — the pre-batch committed
107115
* backing, or the draft's pending backing when a draft preceded the

‎packages/signals/tests/store/projection-root-overlay.test.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ import {
1818
*
1919
* The complexity guard is deterministic, not timed: `cloneRaw` is the only
2020
* store code that calls `Object.getOwnPropertyDescriptors`, so a spy on it
21-
* counts container clones exactly. One clone is legitimate per lifetime —
21+
* counts descriptor clones exactly (plain-data records clone by spread since
22+
* #3360 and register zero). At most one clone is legitimate per lifetime —
2223
* privatizing the user's seed at the first fold (never-mutate-user-data).
2324
*/
2425
const KEYS = 2000;
@@ -100,9 +101,11 @@ describe("projection root writes are O(written) (#3352)", () => {
100101
const spy = clones();
101102
setGone("b");
102103
flush();
103-
// Exactly the one-time seed privatization (the first derive wrote nothing,
104+
// At most the one-time seed privatization (the first derive wrote nothing,
104105
// so no fold had cloned the user's object yet) — not a per-derive clone.
105-
expect(recordClones(spy, "a")).toBe(1);
106+
// A plain-data record clones by spread (#3360), which the descriptor spy
107+
// does not see at all — hence "at most".
108+
expect(recordClones(spy, "a")).toBeLessThanOrEqual(1);
106109
expect("b" in proj).toBe(false);
107110
expect(proj.b).toBeUndefined();
108111
expect(Object.keys(proj)).toEqual(["a", "c"]);
@@ -116,7 +119,7 @@ describe("projection root writes are O(written) (#3352)", () => {
116119
// Now owned: the next derive's root delete opens an overlay, no clone.
117120
setGone("c");
118121
flush();
119-
expect(recordClones(spy, "a")).toBe(1);
122+
expect(recordClones(spy, "a")).toBeLessThanOrEqual(1);
120123
expect(Object.keys(proj)).toEqual(["a"]);
121124
expect(seenKeys).toHaveLength(3);
122125
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Per-write floor of narrow stores (#3360 repro shape): one root key written
2+
// per store, one flush, no subscribers — the cost is pure draft/commit
3+
// bookkeeping. rc.7 paid a descriptor clone (or, over an owned backing, a
4+
// prototype overlay whose flatten wrote into a V8 prototype) plus a
5+
// privatizing clone at the first commit; narrow plain containers now clone by
6+
// spread and swap the clone in. The steady-state case is the number to watch;
7+
// the fresh-store case covers the reporter's exact benchmark.
8+
import { bench, describe } from "vitest";
9+
import { createStore, flush } from "../../src/index.js";
10+
11+
const N = 2000;
12+
13+
describe(`${N} one-key stores, one write each per commit`, () => {
14+
const stores = Array.from({ length: N }, () => createStore({ value: 0 }));
15+
for (const [, set] of stores)
16+
set(d => {
17+
d.value = -1;
18+
});
19+
flush();
20+
let tick = 0;
21+
22+
bench("steady state: owned backings (#3360)", () => {
23+
const v = ++tick;
24+
for (let i = 0; i < N; i++)
25+
stores[i][1](d => {
26+
d.value = v;
27+
});
28+
flush();
29+
});
30+
31+
bench("fresh stores: create + first write + first commit (reporter shape)", () => {
32+
const fresh = Array.from({ length: N }, () => createStore({ value: 0 }));
33+
for (let i = 0; i < N; i++)
34+
fresh[i][1](d => {
35+
d.value = 1;
36+
});
37+
flush();
38+
});
39+
});

0 commit comments

Comments
 (0)