diff --git a/packages/core/src/compiler/svgIdNamespacing.test.ts b/packages/core/src/compiler/svgIdNamespacing.test.ts index 8ee4c46f0e..88e4ac4029 100644 --- a/packages/core/src/compiler/svgIdNamespacing.test.ts +++ b/packages/core/src/compiler/svgIdNamespacing.test.ts @@ -497,6 +497,28 @@ it("looks up only the ids a stylesheet names", () => { expect(sets).toBeLessThan(20_000); }); +// fails without the fix: every read of a scope's size walked every id the scope renames. +it("reads a scope's size without walking its ids, however many styles ask", () => { + const ids = Array.from({ length: 500 }, (_, index) => `c${index}`); + const defs = ids.map((id) => ``).join(""); + const { document, scopes } = scopedDocument([ + { namespace: "a", html: `${defs}` }, + { namespace: "b", html: `${defs}` }, + ]); + const idMap = namespaceCollidingSvgIds(document, scopes)[1]!; + const has = vi.spyOn(Map.prototype, "has"); + let lookups: number; + try { + for (let i = 0; i < 500; i += 1) rewriteSvgIdReferencesInCss(`.s${i} { color: red; }`, idMap); + lookups = has.mock.calls.length; + } finally { + has.mockRestore(); + } + + expect(idMap.size).toBe(500); + expect(lookups).toBeLessThan(500); +}); + // fails without the fix: the whole namespace, however long, prefixed every renamed id. it("caps a long namespace's prefix, each mount's renamed ids still distinct", () => { const long = (end: string) => `${"x".repeat(5000)}${end}`; diff --git a/packages/core/src/compiler/svgIdNamespacing.ts b/packages/core/src/compiler/svgIdNamespacing.ts index c7dd921080..cbff168ac6 100644 --- a/packages/core/src/compiler/svgIdNamespacing.ts +++ b/packages/core/src/compiler/svgIdNamespacing.ts @@ -388,11 +388,18 @@ export type SvgIdMap = Pick, "get" | "has" | "size"> /** One scope's renames read through to the document's shared table, never copied per scope. */ class ScopedIdMap implements SvgIdMap { + readonly size: number; + constructor( private readonly own: ReadonlyMap, private readonly shared: ReadonlyMap, private readonly hidden: ReadonlySet, - ) {} + ) { + let size = own.size + shared.size; + for (const id of own.keys()) if (shared.has(id)) size -= 1; + for (const id of hidden) if (id !== null && !own.has(id) && shared.has(id)) size -= 1; + this.size = size; + } get(id: string): string | undefined { return this.own.get(id) ?? (this.hidden.has(id) ? undefined : this.shared.get(id)); @@ -401,14 +408,6 @@ class ScopedIdMap implements SvgIdMap { has(id: string): boolean { return this.get(id) !== undefined; } - - get size(): number { - let size = this.own.size + this.shared.size; - for (const id of this.own.keys()) if (this.shared.has(id)) size -= 1; - for (const id of this.hidden) - if (id !== null && !this.own.has(id) && this.shared.has(id)) size -= 1; - return size; - } } const attributeBytes = (el: Element): number =>