Skip to content

Commit 7d46d4a

Browse files
committed
feat(Queue): reimplement to improve performance
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
1 parent 7193941 commit 7d46d4a

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

queue.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { Notify } from "./notify.ts";
2-
31
/**
42
* A queue implementation that allows for adding and removing elements, with optional waiting when
53
* popping elements from an empty queue.
@@ -18,7 +16,7 @@ import { Notify } from "./notify.ts";
1816
* ```
1917
*/
2018
export class Queue<T extends NonNullable<unknown> | null> {
21-
#notify = new Notify();
19+
#resolves: (() => void)[] = [];
2220
#items: T[] = [];
2321

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

3836
/**
3937
* Adds an item to the end of the queue and notifies any waiting consumers.
4038
*/
4139
push(value: T): void {
4240
this.#items.push(value);
43-
this.#notify.notify();
41+
this.#resolves.shift()?.();
4442
}
4543

4644
/**
@@ -55,7 +53,12 @@ export class Queue<T extends NonNullable<unknown> | null> {
5553
if (value !== undefined) {
5654
return value;
5755
}
58-
await this.#notify.notified({ signal });
56+
const { promise, resolve, reject } = Promise.withResolvers<void>();
57+
signal?.addEventListener("abort", () => reject(signal.reason), {
58+
once: true,
59+
});
60+
this.#resolves.push(resolve);
61+
await promise;
5962
}
6063
}
6164
}

0 commit comments

Comments
 (0)