Skip to content

Commit

Permalink
feat(Queue): 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 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
  • Loading branch information
lambdalisue committed Aug 16, 2024
1 parent 3e7f6f5 commit b22cb2c
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions queue.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -18,7 +16,7 @@ import { Notify } from "./notify.ts";
* ```
*/
export class Queue<T extends NonNullable<unknown> | null> {
#notify = new Notify();
#resolves: (() => void)[] = [];
#items: T[] = [];

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

/**
* Adds an item to the end of the queue and notifies any waiting consumers.
*/
push(value: T): void {
this.#items.push(value);
this.#notify.notify();
this.#resolves.shift()?.();
}

/**
Expand All @@ -55,7 +53,12 @@ export class Queue<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 b22cb2c

Please sign in to comment.