From 58c9104eddc8b7994a067a97daae5684e42f892f Mon Sep 17 00:00:00 2001 From: Eoghan Murray Date: Tue, 15 Aug 2023 10:39:29 +0100 Subject: [PATCH] Perf: Avoid creation of intermediary array when iterating over style rules (#1272) * Perf: Avoid creation of intermediary array when iterating over stylesheet rules by using the second `mapFn` argument of Array.from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from Performance analysis by: JonasBA Authored-by: Eoghan Murray --- .changeset/nervous-mirrors-perform.md | 6 ++++++ packages/rrweb-snapshot/src/utils.ts | 2 +- packages/rrweb/src/record/stylesheet-manager.ts | 11 ++++------- 3 files changed, 11 insertions(+), 8 deletions(-) create mode 100644 .changeset/nervous-mirrors-perform.md diff --git a/.changeset/nervous-mirrors-perform.md b/.changeset/nervous-mirrors-perform.md new file mode 100644 index 0000000000..46cf31fef8 --- /dev/null +++ b/.changeset/nervous-mirrors-perform.md @@ -0,0 +1,6 @@ +--- +'rrweb-snapshot': patch +'rrweb': patch +--- + +Perf: Avoid creation of intermediary array when iterating over style rules diff --git a/packages/rrweb-snapshot/src/utils.ts b/packages/rrweb-snapshot/src/utils.ts index 02043995fe..95444c18b3 100644 --- a/packages/rrweb-snapshot/src/utils.ts +++ b/packages/rrweb-snapshot/src/utils.ts @@ -98,7 +98,7 @@ export function stringifyStylesheet(s: CSSStyleSheet): string | null { const rules = s.rules || s.cssRules; return rules ? fixBrowserCompatibilityIssuesInCSS( - Array.from(rules).map(stringifyRule).join(''), + Array.from(rules, stringifyRule).join(''), ) : null; } catch (error) { diff --git a/packages/rrweb/src/record/stylesheet-manager.ts b/packages/rrweb/src/record/stylesheet-manager.ts index b517b7202e..6e0a8077b4 100644 --- a/packages/rrweb/src/record/stylesheet-manager.ts +++ b/packages/rrweb/src/record/stylesheet-manager.ts @@ -61,15 +61,12 @@ export class StylesheetManager { let styleId; if (!this.styleMirror.has(sheet)) { styleId = this.styleMirror.add(sheet); - const rules = Array.from(sheet.rules || CSSRule); styles.push({ styleId, - rules: rules.map((r, index) => { - return { - rule: stringifyRule(r), - index, - }; - }), + rules: Array.from(sheet.rules || CSSRule, (r, index) => ({ + rule: stringifyRule(r), + index, + })), }); } else styleId = this.styleMirror.getId(sheet); adoptedStyleSheetData.styleIds.push(styleId);