Skip to content

Commit 7cf99a5

Browse files
committed
lib: priority_queue pre-grow array and avoid holey reads
1 parent cff138c commit 7cf99a5

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

lib/internal/priority_queue.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,12 @@ module.exports = class PriorityQueue {
2626
insert(value) {
2727
const heap = this.#heap;
2828
const pos = ++this.#size;
29-
heap[pos] = value;
3029

31-
if (heap.length === pos)
30+
if (pos === heap.length)
3231
heap.length *= 2;
3332

33+
heap[pos] = value;
34+
3435
this.percolateUp(pos);
3536
}
3637

@@ -45,6 +46,7 @@ module.exports = class PriorityQueue {
4546
percolateDown(pos) {
4647
const compare = this.#compare;
4748
const setPosition = this.#setPosition;
49+
const hasSetPosition = setPosition !== undefined;
4850
const heap = this.#heap;
4951
const size = this.#size;
5052
const hsize = size >> 1;
@@ -62,22 +64,23 @@ module.exports = class PriorityQueue {
6264

6365
if (compare(item, childItem) <= 0) break;
6466

65-
if (setPosition !== undefined)
67+
if (hasSetPosition)
6668
setPosition(childItem, pos);
6769

6870
heap[pos] = childItem;
6971
pos = child;
7072
}
7173

7274
heap[pos] = item;
73-
if (setPosition !== undefined)
75+
if (hasSetPosition)
7476
setPosition(item, pos);
7577
}
7678

7779
percolateUp(pos) {
7880
const heap = this.#heap;
7981
const compare = this.#compare;
8082
const setPosition = this.#setPosition;
83+
const hasSetPosition = setPosition !== undefined;
8184
const item = heap[pos];
8285

8386
while (pos > 1) {
@@ -86,13 +89,13 @@ module.exports = class PriorityQueue {
8689
if (compare(parentItem, item) <= 0)
8790
break;
8891
heap[pos] = parentItem;
89-
if (setPosition !== undefined)
92+
if (hasSetPosition)
9093
setPosition(parentItem, pos);
9194
pos = parent;
9295
}
9396

9497
heap[pos] = item;
95-
if (setPosition !== undefined)
98+
if (hasSetPosition)
9699
setPosition(item, pos);
97100
}
98101

@@ -112,10 +115,10 @@ module.exports = class PriorityQueue {
112115
}
113116

114117
shift() {
118+
if (this.#size === 0)
119+
return;
115120
const heap = this.#heap;
116121
const value = heap[1];
117-
if (value === undefined)
118-
return;
119122

120123
this.removeAt(1);
121124

0 commit comments

Comments
 (0)