From b22cb2c57a265aa4247ab35d3dca4eb3790fc4d2 Mon Sep 17 00:00:00 2001 From: Alisue Date: Sat, 17 Aug 2024 05:22:36 +0900 Subject: [PATCH] feat(Queue): reimplement to improve performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit benchmark time (avg) iter/s (min … max) p75 p99 p995 --------------------------------------------------------------- ----------------------------- group Queue#push/pop current 154.58 µs/iter 6,469.2 (146 µs … 425.71 µs) 151.83 µs 272.96 µs 297.25 µs v1.0.0 1.1 ms/iter 909.4 (917.17 µs … 5.96 ms) 993.5 µs 3.44 ms 3.58 ms summary current 7.11x faster than v1.0.0 --- queue.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/queue.ts b/queue.ts index 59138cb..ab40158 100644 --- a/queue.ts +++ b/queue.ts @@ -1,5 +1,3 @@ -import { Notify } from "./notify.ts"; - /** * A queue implementation that allows for adding and removing elements, with optional waiting when * popping elements from an empty queue. @@ -18,7 +16,7 @@ import { Notify } from "./notify.ts"; * ``` */ export class Queue | null> { - #notify = new Notify(); + #resolves: (() => void)[] = []; #items: T[] = []; /** @@ -32,7 +30,7 @@ export class Queue | null> { * Returns true if the queue is currently locked. */ get locked(): boolean { - return this.#notify.waiterCount > 0; + return this.#resolves.length > 0; } /** @@ -40,7 +38,7 @@ export class Queue | null> { */ push(value: T): void { this.#items.push(value); - this.#notify.notify(); + this.#resolves.shift()?.(); } /** @@ -55,7 +53,12 @@ export class Queue | null> { if (value !== undefined) { return value; } - await this.#notify.notified({ signal }); + const { promise, resolve, reject } = Promise.withResolvers(); + signal?.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + this.#resolves.push(resolve); + await promise; } } }