From bc92f7ca0c5887aa7ca8943b3966a23e92e02c11 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 5 Jun 2024 16:22:32 -0400 Subject: [PATCH] perf(mutation): refactor parent removed detection to iterative procedure (#1489) * perf(mutation): add deep tree benchmark * perf(mutation): use iterative procedure * perf(mutation): run formatter * perf(mutation): add changeset --- .changeset/kind-kids-design.md | 5 +++ packages/rrweb/src/record/mutation.ts | 16 +++++----- .../rrweb/test/benchmark/dom-mutation.test.ts | 6 ++++ .../benchmark-dom-mutation-deep-nested.html | 31 +++++++++++++++++++ 4 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 .changeset/kind-kids-design.md create mode 100644 packages/rrweb/test/html/benchmark-dom-mutation-deep-nested.html diff --git a/.changeset/kind-kids-design.md b/.changeset/kind-kids-design.md new file mode 100644 index 0000000000..764d3fde1c --- /dev/null +++ b/.changeset/kind-kids-design.md @@ -0,0 +1,5 @@ +--- +"rrweb": patch +--- + +Optimize performance of isParentRemoved by converting it to an iterative procedure diff --git a/packages/rrweb/src/record/mutation.ts b/packages/rrweb/src/record/mutation.ts index 860221e22f..3f5ce5b607 100644 --- a/packages/rrweb/src/record/mutation.ts +++ b/packages/rrweb/src/record/mutation.ts @@ -802,15 +802,15 @@ function _isParentRemoved( n: Node, mirror: Mirror, ): boolean { - const { parentNode } = n; - if (!parentNode) { - return false; - } - const parentId = mirror.getId(parentNode); - if (removes.some((r) => r.id === parentId)) { - return true; + let node: ParentNode | null = n.parentNode; + while (node) { + const parentId = mirror.getId(node); + if (removes.some((r) => r.id === parentId)) { + return true; + } + node = node.parentNode; } - return _isParentRemoved(removes, parentNode, mirror); + return false; } function isAncestorInSet(set: Set, n: Node): boolean { diff --git a/packages/rrweb/test/benchmark/dom-mutation.test.ts b/packages/rrweb/test/benchmark/dom-mutation.test.ts index 4bf3109e2c..33bfb2566d 100644 --- a/packages/rrweb/test/benchmark/dom-mutation.test.ts +++ b/packages/rrweb/test/benchmark/dom-mutation.test.ts @@ -18,6 +18,12 @@ const suites: Array< // eval: 'document.querySelector("button").click()', // times: 10, // }, + { + title: 'create 1000x 1 DOM nodes with deeply nested children', + html: 'benchmark-dom-mutation-deep-nested.html', + eval: 'window.workload()', + times: 10, + }, { title: 'create 1000x10 DOM nodes', html: 'benchmark-dom-mutation.html', diff --git a/packages/rrweb/test/html/benchmark-dom-mutation-deep-nested.html b/packages/rrweb/test/html/benchmark-dom-mutation-deep-nested.html new file mode 100644 index 0000000000..fd0a4258b2 --- /dev/null +++ b/packages/rrweb/test/html/benchmark-dom-mutation-deep-nested.html @@ -0,0 +1,31 @@ + + + +