Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 742c910

Browse files
committedAug 16, 2024··
feat(Stack): reimplement to improve performance
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
1 parent 75946e0 commit 742c910

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed
 

‎stack.ts

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { Notify } from "./notify.ts";
2-
31
/**
42
* A stack implementation that allows for adding and removing elements, with optional waiting when
53
* popping elements from an empty stack.
@@ -20,7 +18,7 @@ import { Notify } from "./notify.ts";
2018
* @template T The type of items in the stack.
2119
*/
2220
export class Stack<T extends NonNullable<unknown> | null> {
23-
#notify = new Notify();
21+
#resolves: (() => void)[] = [];
2422
#items: T[] = [];
2523

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

4038
/**
@@ -44,7 +42,7 @@ export class Stack<T extends NonNullable<unknown> | null> {
4442
*/
4543
push(value: T): void {
4644
this.#items.push(value);
47-
this.#notify.notify();
45+
this.#resolves.shift()?.();
4846
}
4947

5048
/**
@@ -59,7 +57,12 @@ export class Stack<T extends NonNullable<unknown> | null> {
5957
if (value !== undefined) {
6058
return value;
6159
}
62-
await this.#notify.notified({ signal });
60+
const { promise, resolve, reject } = Promise.withResolvers<void>();
61+
signal?.addEventListener("abort", () => reject(signal.reason), {
62+
once: true,
63+
});
64+
this.#resolves.push(resolve);
65+
await promise;
6366
}
6467
}
6568
}

0 commit comments

Comments
 (0)
Please sign in to comment.