From 742c910c2da9f953ab38e6006aa596c08dba6ad8 Mon Sep 17 00:00:00 2001 From: Alisue Date: Sat, 17 Aug 2024 05:23:37 +0900 Subject: [PATCH] feat(Stack): 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 Stack#push/pop current 112.37 µs/iter 8,898.9 (100.12 µs … 348.71 µs) 111.25 µs 217.75 µs 225.96 µs v1.0.0 1.07 ms/iter 938.4 (882.54 µs … 3.94 ms) 969.21 µs 3.35 ms 3.55 ms summary current 9.48x faster than v1.0.0 --- stack.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/stack.ts b/stack.ts index 01bb33d..a5876c3 100644 --- a/stack.ts +++ b/stack.ts @@ -1,5 +1,3 @@ -import { Notify } from "./notify.ts"; - /** * A stack implementation that allows for adding and removing elements, with optional waiting when * popping elements from an empty stack. @@ -20,7 +18,7 @@ import { Notify } from "./notify.ts"; * @template T The type of items in the stack. */ export class Stack | null> { - #notify = new Notify(); + #resolves: (() => void)[] = []; #items: T[] = []; /** @@ -34,7 +32,7 @@ export class Stack | null> { * Returns true if the stack is currently locked. */ get locked(): boolean { - return this.#notify.waiterCount > 0; + return this.#resolves.length > 0; } /** @@ -44,7 +42,7 @@ export class Stack | null> { */ push(value: T): void { this.#items.push(value); - this.#notify.notify(); + this.#resolves.shift()?.(); } /** @@ -59,7 +57,12 @@ export class Stack | 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; } } }