From 117c196cde1deef27d0ebdbf87b47b53298accd2 Mon Sep 17 00:00:00 2001 From: David-Emmanuel DIVERNOIS Date: Mon, 23 Sep 2024 13:17:33 +0200 Subject: [PATCH] fix(perf): use array instead of set for queue --- src/index.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index e76bbf8..083051c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -325,7 +325,7 @@ export function asWritable( const triggerUpdate = Symbol(); const queueProcess = Symbol(); let willProcessQueue = false; -const queue = new Set<{ [queueProcess](): void }>(); +const queue: { [queueProcess](): void }[] = []; const MAX_STORE_PROCESSING_IN_QUEUE = 1000; const checkIterations = (iterations: number) => { @@ -385,15 +385,17 @@ export const batch = (fn: () => T): T => { if (needsProcessQueue) { try { const storePasses = new Map<{ [queueProcess](): void }, number>(); - for (const store of queue) { + while (queue.length > 0) { + const store = queue.shift()!; const storeCount = storePasses.get(store) ?? 0; checkIterations(storeCount); storePasses.set(store, storeCount + 1); - queue.delete(store); store[queueProcess](); } } finally { - queue.clear(); + if (queue.length > 0) { + queue.splice(0, queue.length); + } willProcessQueue = false; } } @@ -604,7 +606,10 @@ export abstract class Store implements Readable { protected pauseSubscribers(): void { if (!this.#subscribersPaused) { this.#subscribersPaused = true; - queue.delete(this as any); + const indexInQueue = queue.indexOf(this as any); + if (indexInQueue > -1) { + queue.splice(indexInQueue, 1); + } for (const subscriber of [...this.#subscribers]) { if (subscriber._valueIndex === 0 || subscriber._paused) { // ignore subscribers which were not yet called synchronously or are already paused @@ -628,7 +633,7 @@ export abstract class Store implements Readable { if (this.#subscribersPaused) { this.#subscribersPaused = false; batch(() => { - queue.add(this as any); + queue.push(this as any); }); } }