Skip to content

Commit e978a63

Browse files
authored
lib: optimize priority queue
PR-URL: #60039 Reviewed-By: Juan José Arboleda <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]>
1 parent e6cd8a2 commit e978a63

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

lib/internal/priority_queue.js

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
'use strict';
22

3-
const {
4-
Array,
5-
} = primordials;
6-
73
// The PriorityQueue is a basic implementation of a binary heap that accepts
84
// a custom sorting function via its constructor. This function is passed
95
// the two nodes to compare, similar to the native Array#sort. Crucially
@@ -12,7 +8,7 @@ const {
128

139
module.exports = class PriorityQueue {
1410
#compare = (a, b) => a - b;
15-
#heap = new Array(64);
11+
#heap = [undefined, undefined];
1612
#setPosition;
1713
#size = 0;
1814

@@ -28,9 +24,6 @@ module.exports = class PriorityQueue {
2824
const pos = ++this.#size;
2925
heap[pos] = value;
3026

31-
if (heap.length === pos)
32-
heap.length *= 2;
33-
3427
this.percolateUp(pos);
3528
}
3629

@@ -45,6 +38,7 @@ module.exports = class PriorityQueue {
4538
percolateDown(pos) {
4639
const compare = this.#compare;
4740
const setPosition = this.#setPosition;
41+
const hasSetPosition = setPosition !== undefined;
4842
const heap = this.#heap;
4943
const size = this.#size;
5044
const hsize = size >> 1;
@@ -62,22 +56,23 @@ module.exports = class PriorityQueue {
6256

6357
if (compare(item, childItem) <= 0) break;
6458

65-
if (setPosition !== undefined)
59+
if (hasSetPosition)
6660
setPosition(childItem, pos);
6761

6862
heap[pos] = childItem;
6963
pos = child;
7064
}
7165

7266
heap[pos] = item;
73-
if (setPosition !== undefined)
67+
if (hasSetPosition)
7468
setPosition(item, pos);
7569
}
7670

7771
percolateUp(pos) {
7872
const heap = this.#heap;
7973
const compare = this.#compare;
8074
const setPosition = this.#setPosition;
75+
const hasSetPosition = setPosition !== undefined;
8176
const item = heap[pos];
8277

8378
while (pos > 1) {
@@ -86,13 +81,13 @@ module.exports = class PriorityQueue {
8681
if (compare(parentItem, item) <= 0)
8782
break;
8883
heap[pos] = parentItem;
89-
if (setPosition !== undefined)
84+
if (hasSetPosition)
9085
setPosition(parentItem, pos);
9186
pos = parent;
9287
}
9388

9489
heap[pos] = item;
95-
if (setPosition !== undefined)
90+
if (hasSetPosition)
9691
setPosition(item, pos);
9792
}
9893

0 commit comments

Comments
 (0)