Skip to content

Commit

Permalink
perf(rrweb): attribute mutation optimization (#1343)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdellanoce authored Nov 3, 2023
1 parent 9c6edfe commit 05478c3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/moody-dots-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'rrweb': patch
---

use WeakMap for faster attributeCursor lookup while processing attribute mutations
7 changes: 4 additions & 3 deletions packages/rrweb/src/record/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export default class MutationBuffer {

private texts: textCursor[] = [];
private attributes: attributeCursor[] = [];
private attributeMap = new WeakMap<Node, attributeCursor>();
private removes: removedNodeMutation[] = [];
private mapRemoves: Node[] = [];

Expand Down Expand Up @@ -485,6 +486,7 @@ export default class MutationBuffer {
// reset
this.texts = [];
this.attributes = [];
this.attributeMap = new WeakMap<Node, attributeCursor>();
this.removes = [];
this.addedSet = new Set<Node>();
this.movedSet = new Set<Node>();
Expand Down Expand Up @@ -554,9 +556,7 @@ export default class MutationBuffer {
return;
}

let item: attributeCursor | undefined = this.attributes.find(
(a) => a.node === m.target,
);
let item = this.attributeMap.get(m.target);
if (
target.tagName === 'IFRAME' &&
attributeName === 'src' &&
Expand All @@ -578,6 +578,7 @@ export default class MutationBuffer {
_unchangedStyles: {},
};
this.attributes.push(item);
this.attributeMap.set(m.target, item);
}

// Keep this property on inputs that used to be password inputs
Expand Down
6 changes: 6 additions & 0 deletions packages/rrweb/test/benchmark/dom-mutation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ const suites: Array<
eval: 'window.workload()',
times: 5,
},
{
title: 'modify attributes on 10000 DOM nodes',
html: 'benchmark-dom-mutation-attributes.html',
eval: 'window.workload()',
times: 10,
},
];

function avg(v: number[]): number {
Expand Down
21 changes: 21 additions & 0 deletions packages/rrweb/test/html/benchmark-dom-mutation-attributes.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<html>
<body></body>
<script>
function init() {
const count = 10000;
for (let i = 0; i < count; ++i) {
const div = document.createElement('div');
document.body.appendChild(div);
}
}

init();

window.workload = () => {
const divs = document.getElementsByTagName('div');
for (let div of divs) {
div.classList.add('foo');
}
};
</script>
</html>

0 comments on commit 05478c3

Please sign in to comment.