Skip to content

Commit 0a61bd5

Browse files
fb55claude
andcommitted
perf(tree-adapters): keep the recipient's attribute names between merges
`adoptAttributes` rebuilt a Set of the recipient's attribute names on every merge, so repeated `<html>` or `<body>` start tags took quadratic time: tags without attributes rebuilt it for an element that has many, and a document whose tags each bring a new attribute rebuilt it from a growing list (8,000 such tags: 32 million list reads, about a second). It returns early for an empty list, and the default adapter now keeps, for each attribute list it merged into, a map from each name to its position, and adds the names it appends. The map is reused while the list keeps its length and one name per entry, and while each merged name the map holds still names the entry at that position; otherwise the list is indexed again. A merge costs the attributes it brings, plus one pass over the list the first time and after an edit is seen. Merging a list into itself is a no-op (every name is present; with a stale cached name it would append to the list being read), and a sparse list is indexed around its holes as before. A name found present is therefore always checked against the list. A name found absent is not: when code outside the parser gives an existing entry a new name between two merges without changing the list's length (a rename, a replaced entry, or an insertion plus a removal), and no merged name shows the edit, merging that name appends a second entry for it, where scanning the list on every merge left it out. Parser output alone never does this; it needs a direct caller of the adapter or a `ParserStream` script handler that edits `<html>` or `<body>` attributes before a repeated tag. Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6c705d5 commit 0a61bd5

3 files changed

Lines changed: 149 additions & 1 deletion

File tree

‎packages/parse5-parser-stream/test/parser-stream.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import { ParserStream } from '../lib/index.js';
33
import { generateParsingTests } from 'parse5-test-utils/utils/generate-parsing-tests.js';
44
import { parseChunked } from './utils/parse-chunked.js';
55
import { finished } from 'parse5-test-utils/utils/common.js';
6+
import type { DefaultTreeAdapterTypes } from 'parse5';
7+
8+
type Element = DefaultTreeAdapterTypes.Element;
69

710
generateParsingTests(
811
'ParserStream',
@@ -39,4 +42,23 @@ describe('ParserStream', () => {
3942

4043
assert.throws(() => stream.write(buf), TypeError);
4144
});
45+
46+
it.each([
47+
['merges <html> attributes against the names a script left', 0, '<html a=3 c=3>', 'c=1 b=2 a=3'],
48+
// Pins the default adapter's documented limit: a name a script gives an entry is missed, so it is appended again.
49+
['appends a name a script gave an <html> attribute again', 1, '<html c=3>', 'a=1 c=2 c=3'],
50+
])('%s', async (_name, renamed, tail, expected) => {
51+
const parser = new ParserStream();
52+
53+
parser.on('script', (_scriptElement, _documentWrite, resume) => {
54+
(parser.document.childNodes[0] as Element).attrs[renamed].name = 'c';
55+
resume();
56+
});
57+
parser.end(`<html a=1><html b=2><script></script>${tail}`);
58+
59+
await finished(parser);
60+
61+
const { attrs } = parser.document.childNodes[0] as Element;
62+
assert.strictEqual(attrs.map(({ name, value }) => `${name}=${value}`).join(' '), expected);
63+
});
4264
});
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { it, expect } from 'vitest';
2+
import { parse, defaultTreeAdapter, html, type DefaultTreeAdapterMap, type TreeAdapter } from 'parse5';
3+
4+
type Element = DefaultTreeAdapterMap['element'];
5+
6+
it('merges repeated <html> attributes without rereading the merged list', () => {
7+
const n = 512;
8+
let reads = 0;
9+
const treeAdapter: TreeAdapter<DefaultTreeAdapterMap> = {
10+
...defaultTreeAdapter,
11+
createElement(tagName, namespaceURI, attrs) {
12+
const counted = new Proxy(attrs, {
13+
get(target, key, receiver): unknown {
14+
if (typeof key === 'string' && /^\d+$/.test(key)) reads++;
15+
return Reflect.get(target, key, receiver);
16+
},
17+
});
18+
return defaultTreeAdapter.createElement(tagName, namespaceURI, tagName === 'html' ? counted : attrs);
19+
},
20+
};
21+
const document = parse(Array.from({ length: n }, (_, i) => `<html a${i}=v>`).join(''), { treeAdapter });
22+
expect(reads).toBeLessThan(4 * n);
23+
expect((document.childNodes[0] as Element).attrs).toHaveLength(n);
24+
});
25+
26+
it.each<[string, (element: Element) => void, string]>([
27+
[
28+
'an attribute is added to the list',
29+
(element): void => {
30+
element.attrs.push({ name: 'c', value: '0' });
31+
},
32+
'a=1 b=2 c=0 d=3',
33+
],
34+
[
35+
'the list is replaced',
36+
(element): void => {
37+
element.attrs = [
38+
{ name: 'a', value: '0' },
39+
{ name: 'c', value: '0' },
40+
];
41+
},
42+
'a=0 c=0 d=3',
43+
],
44+
[
45+
'an entry becomes a hole',
46+
(element): void => {
47+
delete element.attrs[0];
48+
},
49+
'b=2 a=3 c=3 d=3',
50+
],
51+
[
52+
'a merge that repeats a name and a removal',
53+
(element): void => {
54+
defaultTreeAdapter.adoptAttributes(element, [
55+
{ name: 'c', value: '1' },
56+
{ name: 'c', value: '2' },
57+
{ name: 'd', value: '1' },
58+
]);
59+
element.attrs.pop();
60+
},
61+
'a=1 b=2 c=1 c=2 d=3',
62+
],
63+
])('adopts only the attributes the list lacks after %s', (_name, edit, expected) => {
64+
const element = defaultTreeAdapter.createElement('html', html.NS.HTML, [{ name: 'a', value: '1' }]);
65+
defaultTreeAdapter.adoptAttributes(element, [{ name: 'b', value: '2' }]);
66+
edit(element);
67+
defaultTreeAdapter.adoptAttributes(element, [
68+
{ name: 'a', value: '3' },
69+
{ name: 'c', value: '3' },
70+
{ name: 'd', value: '3' },
71+
]);
72+
// One row leaves a hole in the list, which the merge skips.
73+
expect(
74+
element.attrs
75+
.filter((attr) => attr !== undefined)
76+
.map(({ name, value }) => `${name}=${value}`)
77+
.join(' '),
78+
).toBe(expected);
79+
});
80+
81+
it('leaves a list alone when it is merged into itself', () => {
82+
const element = defaultTreeAdapter.createElement('html', html.NS.HTML, [{ name: 'a', value: '1' }]);
83+
defaultTreeAdapter.adoptAttributes(element, [{ name: 'b', value: '2' }]);
84+
// A renamed entry is unknown to the cache; merging the list into itself must not append it to itself.
85+
element.attrs[1].name = 'c';
86+
defaultTreeAdapter.adoptAttributes(element, element.attrs);
87+
expect(element.attrs.map(({ name, value }) => `${name}=${value}`).join(' ')).toBe('a=1 c=2');
88+
});

‎packages/parse5/lib/tree-adapters/default.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,9 @@ export type DefaultTreeAdapterMap = TreeAdapterTypeMap<
102102
DocumentType
103103
>;
104104

105+
/** The position of each name in the attribute lists `adoptAttributes` merged into, kept for the next merge into that list. */
106+
const attrListIndexes = new WeakMap<Attribute[], Map<string, number>>();
107+
105108
export const defaultTreeAdapter: TreeAdapter<DefaultTreeAdapterMap> = {
106109
//Node construction
107110
createDocument(): Document {
@@ -236,14 +239,49 @@ export const defaultTreeAdapter: TreeAdapter<DefaultTreeAdapterMap> = {
236239
}
237240
},
238241

242+
/**
243+
* Keeps the recipient's names between merges as a map from name to position. The map is rebuilt when the list changed
244+
* length or has a repeated name, or when a merged name it holds no longer names the entry at that position. A name that
245+
* other code gives an existing entry between two merges is missed otherwise, and merging it appends it a second time.
246+
*/
239247
adoptAttributes(recipient: Element, attrs: Attribute[]): void {
240-
const recipientAttrsMap = new Set(recipient.attrs.map((attr) => attr.name));
248+
// Merging a list into itself adds nothing: every name is already present.
249+
if (attrs.length === 0 || attrs === recipient.attrs) return;
250+
251+
const cached = attrListIndexes.get(recipient.attrs);
252+
const isIndexed =
253+
cached?.size === recipient.attrs.length &&
254+
attrs.every(({ name }) => {
255+
const index = cached.get(name);
256+
return index === undefined || recipient.attrs[index]?.name === name;
257+
});
258+
const recipientAttrsMap = isIndexed ? cached : new Map<string, number>();
259+
260+
if (!isIndexed) {
261+
for (let i = 0; i < recipient.attrs.length; i++) {
262+
const attr = recipient.attrs[i];
263+
// A sparse list is indexed again on every merge, as its size never matches its length.
264+
if (attr !== undefined) recipientAttrsMap.set(attr.name, i);
265+
}
266+
attrListIndexes.set(recipient.attrs, recipientAttrsMap);
267+
}
268+
269+
const adoptedFrom = recipient.attrs.length;
241270

242271
for (let j = 0; j < attrs.length; j++) {
243272
if (!recipientAttrsMap.has(attrs[j].name)) {
244273
recipient.attrs.push(attrs[j]);
245274
}
246275
}
276+
277+
for (let j = adoptedFrom; j < recipient.attrs.length; j++) {
278+
recipientAttrsMap.set(recipient.attrs[j].name, j);
279+
}
280+
281+
// A list with a repeated name is indexed again on the next merge.
282+
if (recipientAttrsMap.size !== recipient.attrs.length) {
283+
attrListIndexes.delete(recipient.attrs);
284+
}
247285
},
248286

249287
//Tree traversing

0 commit comments

Comments
 (0)