Skip to content

Commit 05478c3

Browse files
authored
perf(rrweb): attribute mutation optimization (#1343)
1 parent 9c6edfe commit 05478c3

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

.changeset/moody-dots-refuse.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'rrweb': patch
3+
---
4+
5+
use WeakMap for faster attributeCursor lookup while processing attribute mutations

packages/rrweb/src/record/mutation.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ export default class MutationBuffer {
142142

143143
private texts: textCursor[] = [];
144144
private attributes: attributeCursor[] = [];
145+
private attributeMap = new WeakMap<Node, attributeCursor>();
145146
private removes: removedNodeMutation[] = [];
146147
private mapRemoves: Node[] = [];
147148

@@ -485,6 +486,7 @@ export default class MutationBuffer {
485486
// reset
486487
this.texts = [];
487488
this.attributes = [];
489+
this.attributeMap = new WeakMap<Node, attributeCursor>();
488490
this.removes = [];
489491
this.addedSet = new Set<Node>();
490492
this.movedSet = new Set<Node>();
@@ -554,9 +556,7 @@ export default class MutationBuffer {
554556
return;
555557
}
556558

557-
let item: attributeCursor | undefined = this.attributes.find(
558-
(a) => a.node === m.target,
559-
);
559+
let item = this.attributeMap.get(m.target);
560560
if (
561561
target.tagName === 'IFRAME' &&
562562
attributeName === 'src' &&
@@ -578,6 +578,7 @@ export default class MutationBuffer {
578578
_unchangedStyles: {},
579579
};
580580
this.attributes.push(item);
581+
this.attributeMap.set(m.target, item);
581582
}
582583

583584
// Keep this property on inputs that used to be password inputs

packages/rrweb/test/benchmark/dom-mutation.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ const suites: Array<
4242
eval: 'window.workload()',
4343
times: 5,
4444
},
45+
{
46+
title: 'modify attributes on 10000 DOM nodes',
47+
html: 'benchmark-dom-mutation-attributes.html',
48+
eval: 'window.workload()',
49+
times: 10,
50+
},
4551
];
4652

4753
function avg(v: number[]): number {
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<html>
2+
<body></body>
3+
<script>
4+
function init() {
5+
const count = 10000;
6+
for (let i = 0; i < count; ++i) {
7+
const div = document.createElement('div');
8+
document.body.appendChild(div);
9+
}
10+
}
11+
12+
init();
13+
14+
window.workload = () => {
15+
const divs = document.getElementsByTagName('div');
16+
for (let div of divs) {
17+
div.classList.add('foo');
18+
}
19+
};
20+
</script>
21+
</html>

0 commit comments

Comments
 (0)