Skip to content

Commit

Permalink
feat(Stack): reimplement to improve performance
Browse files Browse the repository at this point in the history
  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
  • Loading branch information
lambdalisue committed Aug 16, 2024
1 parent 93c3ebb commit 02617d0
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions stack.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -20,7 +18,7 @@ import { Notify } from "./notify.ts";
* @template T The type of items in the stack.
*/
export class Stack<T extends NonNullable<unknown> | null> {
#notify = new Notify();
#resolves: (() => void)[] = [];
#items: T[] = [];

/**
Expand All @@ -34,7 +32,7 @@ export class Stack<T extends NonNullable<unknown> | null> {
* Returns true if the stack is currently locked.
*/
get locked(): boolean {
return this.#notify.waiterCount > 0;
return this.#resolves.length > 0;
}

/**
Expand All @@ -44,7 +42,7 @@ export class Stack<T extends NonNullable<unknown> | null> {
*/
push(value: T): void {
this.#items.push(value);
this.#notify.notify();
this.#resolves.shift()?.();
}

/**
Expand All @@ -59,7 +57,12 @@ export class Stack<T extends NonNullable<unknown> | null> {
if (value !== undefined) {
return value;
}
await this.#notify.notified({ signal });
const { promise, resolve, reject } = Promise.withResolvers<void>();
signal?.addEventListener("abort", () => reject(signal.reason), {
once: true,
});
this.#resolves.push(resolve);
await promise;
}
}
}

0 comments on commit 02617d0

Please sign in to comment.