Skip to content

Commit e10a4ba

Browse files
ryansolidClaude via Cursorcursoragent
authored
perf(ssr): spread-element tails as markup, hoisted spread sources, ssrElement/merge at the writer floor (#3562)
* perf(ssr): spread elements — trailing attributes as markup, source literals hoisted, ssrElement/merge fast paths Compilers (Babel + Oxc, byte-identical): - Attributes after an element's last spread are markup, not a source. `<li {...rest} class="row" data-id={id}>` compiles to ssrElement("li", rest, …, _sk$, () => ' class="row"' + ssrElementAttribute("data-id", id)) with a hoisted skip predicate per key set; the string is a literal when every part is static. No later source can override a trailing attribute, so output is unchanged. Child properties, textarea value, reserved namespaces and JSX-valued attributes stay sources. - A spread element's source literal with getters (`<li data-id={id} class="row" {...rest}>`) is marked for hoistProps and compiles to the same hoisted constructor as component props. Runtime (@solidjs/web): - ssrElement takes an optional trailing `attrs`: a string, or a thunk called after the source walk and before the children — where the trailing source's getters were read, so hydration ids keep their order (spec: a server memo in the tail yields the same _hk sequence as the getter and template forms). - ssrElementAttribute(key, value): one attribute by the spread walk's rules, for compiler-emitted tail thunks. - Void-tag test and attribute-name escape cached per name; plain single source read and keyed in place. Runtime (@solidjs/signals): - merge(): presized source arrays; the get trap walks plain sources directly, reading before the `in` check. spread-static-tail server bench, 500 rows (ops/s, Babel): tail {...a} class 5,038 -> 5,057 head class {...a} 3,646 -> 3,661 mixed {...a} class data={id} 3,115 -> 3,790 (hoisted source) -> 4,437 (thunk) 1.42x dynhead data={id} class {...a} 2,821 -> 3,418 1.21x Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> * perf(web): ssrElement remembers one record per tag and reads every source body directly Per tag name one cached TagInfo — `<tag`, `</tag>`, void, textarea, raw-text — in place of building both strings and testing the name per element (the tag work was 13 of the 22 ns/element over a hand-written writer). The source-kind dispatch leaves the key loop: sourceGet was `s[key]` for every kind ssrElement sees, so each body is read as props[prop]; only the key list depends on kind (Reflect.ownKeys through one trap for a store/foreign proxy, as sourceKeys did, else Object.keys). No second loop, no output change. Isolation (btn-variant inputs vs a yak-shaped writer): 70 -> 60 µs/1000 elements, 1.46x -> 1.18x, 22 -> 9 ns/element. Test: a store and a foreign proxy as the single source are walked through one ownKeys trap and get, never a descriptor trap. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> * fix(signals): narrow the merge trap's table state so the package typechecks The inlined read trap kept `view.table` (number | Map | null) in one binding through the branch that reaches `table.get`, so `pnpm build` in signals exited 2 while rollup still emitted JS. Read the state once and give the table its own binding. Co-authored-by: Cursor <[email protected]> * perf(signals): one `$RECORD` read classifies a proxy source — views answer their record, stores answer undefined on the fast path A `$PROXY`-marked source was classified by `$TARGET`, then `$VIEW`, then `$OMIT`: two to four trap hops per source at every merge(), omit(), isStatic and ssrElement. One brand symbol the merge and omit traps answer first and the store trap answers undefined in its symbol branch replaces the three private ones. merge over an omit view 81 → 50 ns, omit over a merge 63 → 36 ns, ssrElement on a view −8%. A branded proxy that predates the key forwards it to a target without it: still a leaf, one read. Co-authored-by: Cursor <[email protected]> * chore(size): audit note for ssrElement/merge at the writer floor (#3562) signals: + createStore: cap unchanged at 16.90 KB (set by #3584), measured at 16,891 B against next's 16,866 (+25 B; 9 B under the cap) — merge()'s presized source arrays and the $RECORD classification in store/utils.ts. Every other scenario is within its cap: core floor 0 B, isPending/latest +31 B, every-store-family app +32 B, CSR observe +11 B (prop mangler short names / brotli layout), the rest 0 B. The observe + attribution cap was re-set by #3587 on next; this PR adds 0 B there. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 28fcc9b commit e10a4ba

32 files changed

Lines changed: 2332 additions & 965 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@solidjs/web": patch
3+
"@solidjs/signals": patch
4+
---
5+
6+
SSR element and props-view fast paths for the per-element hot path. `ssrElement` takes an optional trailing `attrs` — attribute markup the caller already holds (a spread element's trailing attributes, a class a library computed and knows is clean), a string or a thunk called after the sources are walked — appended after the props' attributes in place of a `{ class, style }` source that was built, keyed and precedence-walked on every render; `ssrElementAttribute(key, value)` (compiler primitive) serializes one attribute by the spread walk's rules for such a thunk. Per tag name, `ssrElement` remembers one record — the `<tag` and `</tag>` markup, void, textarea, raw-text — in place of building both strings and testing the name on every element; the attribute-name escape is remembered per name; and every source body is read as `props[prop]` (a plain read or the proxy's trap, which is all the source helper did for these kinds), with only the key list depending on the source's kind. On a button with four props, a skip predicate and a computed class, `ssrElement` runs within 9 ns/element of a hand-written writer that knows its tag and keys (from 22). `merge()` sizes its source arrays up front and its `get` trap walks plain sources directly, reading before the `in` check. A `$PROXY`-marked source is classified by ONE read of a new internal brand, `$RECORD` — a merge or omit view answers its record, a store answers `undefined` on its symbol fast path, a proxy that does not know the key forwards it to a target without it — where `$TARGET` and then each view kind was two to four trap hops per source at every `merge()`, `omit()`, `isStatic` and `ssrElement` (a merge over an omit view: 81 → 50 ns; an omit over a merge: 63 → 36 ns; `ssrElement` on a view: −8%). The private `$SOURCES`/`$OMIT`/`$VIEW` symbols are retired for it; a store-shaped proxy that implements the brand protocol should answer `$RECORD` with `undefined` to keep the read off its generic path. No output changes.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@solidjs/babel-plugin": patch
3+
"@solidjs/compiler": patch
4+
---
5+
6+
SSR: attributes written after an element's last spread are markup, not a source. `<li {...rest} class="row" data-id={id}>` compiles to `ssrElement("li", rest, …, _sk$, () => ' class="row"' + ssrElementAttribute("data-id", id))` — statics written as the template path writes them, dynamics through `ssrElementAttribute` (the spread walk's rules for one key), the whole string a literal when every part is static — with a hoisted skip predicate (`var _sk$ = k => k === "class" || k === "data-id"`, one per key set) so the spread's own copies of those keys are never read or emitted. No later source can override a trailing attribute, so the output is unchanged; the thunk runs where the trailing source's getters used to be read, so hydration ids keep their order. What goes away per element is the trailing object literal (with getters, a dictionary-mode object and a closure per getter), its key list, and the precedence check on every key of the spread — an element whose only other source is the spread now serializes from one plain object. Attributes before a spread stay a source, and a source literal with getters (`<li data-id={id} class="row" {...rest}>`) now compiles to the same hoisted constructor as a component's props (`hoistProps`). Spread-static-tail server bench, 500 rows: statics after the spread 1.31×; a dynamic and a static after the spread 1.42× (1.22× from the hoisted source form, 1.17× from the thunk on top); the same attributes before the spread 1.21×. Child properties (`innerHTML`, `textContent`, `children`), a textarea's `value`, reserved namespaces and JSX-valued attributes stay sources.

‎packages/babel-plugin/src/shared/postprocess.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as t from "@babel/types";
22
import { getRendererConfig, registerImportMethod } from "./utils";
33
import { appendTemplates as appendTemplatesDOM } from "../dom/template";
4-
import { appendTemplates as appendTemplatesSSR } from "../ssr/template";
4+
import { appendTemplates as appendTemplatesSSR, appendSkips } from "../ssr/template";
55
import { isInvalidMarkup } from "./validate";
66
import { hoistProps, takeHoistedProps } from "../ssr/props";
77
import type { NodePath } from "@babel/traverse";
@@ -23,6 +23,9 @@ export default (path: NodePath<t.Program>, state: PluginPass) => {
2323
const hoisted = takeHoistedProps(path);
2424
if (hoisted) path.node.body.unshift(...hoisted);
2525
}
26+
// Spread-element skip predicates sit between the templates and the hoisted
27+
// props shapes (unshifted after them, before the templates unshift).
28+
if (data.ssrSkips?.length) appendSkips(path, data.ssrSkips);
2629

2730
if (data.events) {
2831
path.node.body.push(

‎packages/babel-plugin/src/ssr/element.ts‎

Lines changed: 124 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import {
2323
} from "../shared/utils";
2424
import { transformNode, getCreateTemplate } from "../shared/transform";
2525
import { decodedAttrValue } from "../universal/element";
26-
import { createTemplate } from "./template";
26+
import { createTemplate, registerSkip } from "./template";
27+
import { markPropsLiteral } from "./props";
2728
import type {
2829
BabelPath,
2930
JSXNode,
@@ -987,18 +988,47 @@ function createElement(
987988
});
988989

989990
let props: babelTypes.Expression[];
991+
// Attributes written AFTER the last spread are markup, not a source: no
992+
// later source can override them, so they go to `ssrElement` as its
993+
// attribute string and their keys are skipped on every source — the
994+
// spread's own copy of `class` is never read or emitted, exactly as if they
995+
// were the winning last source. A static is written as the template path
996+
// writes it; a dynamic one is `ssrElementAttribute(key, expr)`, the spread
997+
// walk's own rules for one key, and makes the string a thunk that
998+
// `ssrElement` calls after the walk — the point where the trailing source's
999+
// getters were read, so the expressions keep their place in the
1000+
// hydration-id sequence. What goes away per element is the trailing object
1001+
// literal (with getters, a dictionary-mode object and a closure per
1002+
// getter), its key list, and the "does a later source own this key" check
1003+
// on every key of the spread; an element whose only other source is the
1004+
// spread serializes from ONE plain object. Attributes before a spread stay
1005+
// a source: the spread may override them, and only the runtime knows its
1006+
// keys.
1007+
const tail: Array<string | babelTypes.Expression> = [];
1008+
const skipKeys: string[] = [];
9901009
if (propAttributes.length === 1 && t.isJSXSpreadAttribute(propAttributes[0].node)) {
9911010
props = [propAttributes[0].node.argument];
9921011
} else {
9931012
props = [];
9941013
let runningObject: Array<babelTypes.ObjectProperty | babelTypes.ObjectMethod> = [],
9951014
hasChildren = path.node.children.length > 0;
1015+
// A source object with getters is the same shape as a component's props
1016+
// literal, and a candidate for the same hoisted constructor (ssr/props.ts).
1017+
const sourceLiteral = (properties: typeof runningObject) => {
1018+
const literal = t.objectExpression(properties);
1019+
markPropsLiteral(literal, path, config);
1020+
return literal;
1021+
};
1022+
let lastSpread = -1;
1023+
attributes.forEach((attribute, i) => {
1024+
if (t.isJSXSpreadAttribute(attribute.node)) lastSpread = i;
1025+
});
9961026

997-
attributes.forEach(attribute => {
1027+
attributes.forEach((attribute, i) => {
9981028
const node = attribute.node;
9991029
if (t.isJSXSpreadAttribute(node)) {
10001030
if (runningObject.length) {
1001-
props.push(t.objectExpression(runningObject));
1031+
props.push(sourceLiteral(runningObject));
10021032
runningObject = [];
10031033
}
10041034
// A dynamic spread defers behind a thunk: evaluated in argument
@@ -1024,6 +1054,16 @@ function createElement(
10241054
if (hasChildren && key === "children") return;
10251055
if (key === "ref") return;
10261056
if (key.startsWith("prop:") || key.startsWith("on")) return;
1057+
if (i > lastSpread) {
1058+
const part = tailAttribute(path, tagName, key, node);
1059+
if (part !== undefined) {
1060+
if (typeof part === "string" && typeof tail[tail.length - 1] === "string")
1061+
tail[tail.length - 1] += part;
1062+
else tail.push(part);
1063+
skipKeys.push(key);
1064+
return;
1065+
}
1066+
}
10271067
if (t.isJSXExpressionContainer(value)) {
10281068
if (t.isJSXEmptyExpression(value.expression)) return;
10291069
const expression = value.expression as babelTypes.Expression;
@@ -1047,7 +1087,7 @@ function createElement(
10471087
}
10481088
});
10491089

1050-
if (runningObject.length || !props.length) props.push(t.objectExpression(runningObject));
1090+
if (runningObject.length || !props.length) props.push(sourceLiteral(runningObject));
10511091

10521092
// Several sources go as an ARRAY, not a mergeProps() call: ssrElement
10531093
// serializes straight from the sources (later wins per key, only the
@@ -1058,22 +1098,86 @@ function createElement(
10581098
if (props.length > 1) props = [t.arrayExpression(props)];
10591099
}
10601100

1061-
const exprs = [
1062-
t.callExpression(registerImportMethod(path, "ssrElement"), [
1063-
t.stringLiteral(tagName),
1064-
props[0],
1065-
childNodes.length
1066-
? hydratable
1067-
? t.arrowFunctionExpression(
1068-
[],
1069-
childNodes.length === 1 ? childNodes[0] : t.arrayExpression(childNodes)
1070-
)
1071-
: childNodes.length === 1
1072-
? childNodes[0]
1073-
: t.arrayExpression(childNodes)
1074-
: t.identifier("undefined"),
1075-
t.booleanLiteral(Boolean(topLevel && config.hydratable))
1076-
])
1101+
const args: babelTypes.Expression[] = [
1102+
t.stringLiteral(tagName),
1103+
props[0],
1104+
childNodes.length
1105+
? hydratable
1106+
? t.arrowFunctionExpression(
1107+
[],
1108+
childNodes.length === 1 ? childNodes[0] : t.arrayExpression(childNodes)
1109+
)
1110+
: childNodes.length === 1
1111+
? childNodes[0]
1112+
: t.arrayExpression(childNodes)
1113+
: t.identifier("undefined"),
1114+
t.booleanLiteral(Boolean(topLevel && config.hydratable))
10771115
];
1116+
// The tail rides as `ssrElement`'s skip predicate (hoisted, one per key
1117+
// set) and attribute string — a literal when every part is static, else a
1118+
// thunk concatenating the parts in source order. A `false` static bakes to
1119+
// no markup but still skips its key.
1120+
if (skipKeys.length) {
1121+
let markup: babelTypes.Expression;
1122+
if (tail.every(part => typeof part === "string")) markup = t.stringLiteral(tail.join(""));
1123+
else {
1124+
let concat: babelTypes.Expression | undefined;
1125+
for (const part of tail) {
1126+
const expr = typeof part === "string" ? t.stringLiteral(part) : part;
1127+
concat = concat ? t.binaryExpression("+", concat, expr) : expr;
1128+
}
1129+
markup = t.arrowFunctionExpression([], concat!);
1130+
}
1131+
args.push(registerSkip(path, skipKeys), markup);
1132+
}
1133+
const exprs = [t.callExpression(registerImportMethod(path, "ssrElement"), args)];
10781134
return { exprs, template: "", declarations: [], dynamics: [], spreadElement: true };
10791135
}
1136+
1137+
/**
1138+
* What an attribute after an element's last spread contributes to
1139+
* `ssrElement`'s attribute string. A static is written as the template path
1140+
* writes the same attribute (`transformAttributes`' static branch): a bare or
1141+
* `true` attribute as ` key`, a string or number as ` key="value"` with the
1142+
* value attribute-escaped and class/style whitespace normalized, `false` as
1143+
* nothing. An expression is `ssrElementAttribute("key", expr)` — the spread
1144+
* walk's rules for one key, evaluated when `ssrElement` calls the thunk.
1145+
* `undefined` when the attribute is content rather than markup and must stay
1146+
* a source: a child property (`innerHTML`, `textContent`, `children`), a
1147+
* textarea's value (its text content on the server), a reserved namespace,
1148+
* or a JSX value.
1149+
*/
1150+
function tailAttribute(
1151+
path: BabelPath,
1152+
tagName: string,
1153+
key: string,
1154+
node: babelTypes.JSXAttribute
1155+
): string | babelTypes.Expression | undefined {
1156+
if (
1157+
ChildProperties.has(key) ||
1158+
key === "$ServerOnly" ||
1159+
(tagName === "textarea" && (key === "value" || key === "defaultValue")) ||
1160+
(t.isJSXNamespacedName(node.name) && reservedNameSpaces.has(node.name.namespace.name))
1161+
)
1162+
return undefined;
1163+
const value = node.value;
1164+
const literal: babelTypes.Node | null | undefined = t.isJSXExpressionContainer(value)
1165+
? value.expression
1166+
: value;
1167+
if (literal == null) return ` ${key}`;
1168+
if (t.isBooleanLiteral(literal)) return literal.value ? ` ${key}` : "";
1169+
if (t.isStringLiteral(literal) || t.isNumericLiteral(literal)) {
1170+
let text = String(literal.value);
1171+
if (key === "style" || key === "class") {
1172+
text = trimWhitespace(text);
1173+
if (key === "style") text = text.replace(/; /g, ";").replace(/: /g, ":");
1174+
}
1175+
return text === "" ? ` ${key}` : ` ${key}="${escapeHTML(text, true)}"`;
1176+
}
1177+
if (t.isJSXEmptyExpression(literal) || t.isJSXElement(literal) || t.isJSXFragment(literal))
1178+
return undefined;
1179+
return t.callExpression(registerImportMethod(path, "ssrElementAttribute"), [
1180+
t.stringLiteral(key),
1181+
literal as babelTypes.Expression
1182+
]);
1183+
}

‎packages/babel-plugin/src/ssr/template.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as t from "@babel/types";
22
import { getConfig, isStatementVariableInitializer, registerImportMethod } from "../shared/utils";
33
import type { NodePath } from "@babel/traverse";
4-
import type { ProgramScopeData, TemplateRecord, TransformResult } from "../types";
4+
import type { ProgramScopeData, SkipRecord, TemplateRecord, TransformResult } from "../types";
55

66
type SSRDeclarator = t.VariableDeclarator & { id: t.LVal; init: t.Expression };
77

@@ -150,3 +150,36 @@ export function appendTemplates(path: NodePath<t.Program>, templates: TemplateRe
150150
});
151151
path.node.body.unshift(t.variableDeclaration("var", declarators));
152152
}
153+
154+
/**
155+
* The `skip` predicate of an `ssrElement` call whose static tail attributes
156+
* were baked into its attribute string (ssr/element.ts `createElement`):
157+
* `k => k === "a" || k === "b"` over the baked keys, so the spread's own
158+
* copies of them are never read or emitted. Hoisted to the module like a
159+
* template — one function per distinct key set, shared by every element that
160+
* bakes the same keys — so the call site allocates nothing per render.
161+
*/
162+
export function registerSkip(path: NodePath, keys: string[]): t.Identifier {
163+
const data = path.scope.getProgramParent().data as ProgramScopeData;
164+
const skips = data.ssrSkips || (data.ssrSkips = []);
165+
const key = keys.join("\0");
166+
const found = skips.find(s => s.key === key);
167+
if (found) return found.id;
168+
const id = path.scope.generateUidIdentifier("sk$");
169+
const k = t.identifier("k");
170+
let test: t.Expression = t.binaryExpression("===", k, t.stringLiteral(keys[0]));
171+
for (let i = 1; i < keys.length; i++) {
172+
test = t.logicalExpression("||", test, t.binaryExpression("===", k, t.stringLiteral(keys[i])));
173+
}
174+
skips.push({ key, id, predicate: t.arrowFunctionExpression([t.identifier("k")], test) });
175+
return id;
176+
}
177+
178+
export function appendSkips(path: NodePath<t.Program>, skips: SkipRecord[]) {
179+
path.node.body.unshift(
180+
t.variableDeclaration(
181+
"var",
182+
skips.map(s => t.variableDeclarator(s.id, s.predicate))
183+
)
184+
);
185+
}

‎packages/babel-plugin/src/types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,19 @@ export interface TemplateRecord {
1818
path?: NodePath;
1919
}
2020

21+
/** A hoisted `ssrElement` skip predicate (ssr/template.ts `registerSkip`). */
22+
export interface SkipRecord {
23+
/** The baked key set, `\0`-joined — the dedupe key. */
24+
key: string;
25+
id: t.Identifier;
26+
predicate: t.ArrowFunctionExpression;
27+
}
28+
2129
export interface ProgramScopeData {
2230
imports?: Map<string, t.Identifier>;
2331
templates?: TemplateRecord[];
32+
/** SSR spread-element skip predicates, placed by postprocess. */
33+
ssrSkips?: SkipRecord[];
2434
events?: Set<string>;
2535
/** SSR hoisted props shapes (ssr/props.ts), placed by postprocess. */
2636
hoistedProps?: t.Statement[];

‎packages/babel-plugin/test/__ssr_fixtures__/attributeExpressions/code.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,3 +444,20 @@ const template97 = (
444444
<div {...spread}>{"a < b"}</div>
445445
</>
446446
);
447+
448+
// Static attributes after the last spread bake into ssrElement's attribute
449+
// string with their keys skipped on the spread; statics before a spread, and
450+
// anything between two spreads, stay a source the spread can override.
451+
const template110 = <li {...spread} class="row" data-kind="item" />;
452+
const template111 = <li class="row" data-kind="item" {...spread} />;
453+
const template112 = (
454+
<li {...spread} class="row" data-id={dynamicAttribute()}>
455+
{dynamicContent()}
456+
</li>
457+
);
458+
const template113 = <div {...first} class="x" {...second} id="y" />;
459+
const template114 = (
460+
<input {...spread} disabled={false} type="text" tabindex={0} style=" color: red; top: 0 " />
461+
);
462+
const template115 = <textarea {...spread} innerHTML="<b>x</b>" />;
463+
const template116 = <li {...spread} class="row" data-kind="item" ref={link} />;

0 commit comments

Comments
 (0)