lib: optimize priority queue

PR-URL: https://github.com/nodejs/node/pull/60039
Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Gürgün Dayıoğlu
2025-10-04 22:08:00 +02:00
committed by GitHub
parent e6cd8a21e7
commit e978a63b01

View File

@@ -1,9 +1,5 @@
'use strict';
const {
Array,
} = primordials;
// The PriorityQueue is a basic implementation of a binary heap that accepts
// a custom sorting function via its constructor. This function is passed
// the two nodes to compare, similar to the native Array#sort. Crucially
@@ -12,7 +8,7 @@ const {
module.exports = class PriorityQueue {
#compare = (a, b) => a - b;
#heap = new Array(64);
#heap = [undefined, undefined];
#setPosition;
#size = 0;
@@ -28,9 +24,6 @@ module.exports = class PriorityQueue {
const pos = ++this.#size;
heap[pos] = value;
if (heap.length === pos)
heap.length *= 2;
this.percolateUp(pos);
}
@@ -45,6 +38,7 @@ module.exports = class PriorityQueue {
percolateDown(pos) {
const compare = this.#compare;
const setPosition = this.#setPosition;
const hasSetPosition = setPosition !== undefined;
const heap = this.#heap;
const size = this.#size;
const hsize = size >> 1;
@@ -62,7 +56,7 @@ module.exports = class PriorityQueue {
if (compare(item, childItem) <= 0) break;
if (setPosition !== undefined)
if (hasSetPosition)
setPosition(childItem, pos);
heap[pos] = childItem;
@@ -70,7 +64,7 @@ module.exports = class PriorityQueue {
}
heap[pos] = item;
if (setPosition !== undefined)
if (hasSetPosition)
setPosition(item, pos);
}
@@ -78,6 +72,7 @@ module.exports = class PriorityQueue {
const heap = this.#heap;
const compare = this.#compare;
const setPosition = this.#setPosition;
const hasSetPosition = setPosition !== undefined;
const item = heap[pos];
while (pos > 1) {
@@ -86,13 +81,13 @@ module.exports = class PriorityQueue {
if (compare(parentItem, item) <= 0)
break;
heap[pos] = parentItem;
if (setPosition !== undefined)
if (hasSetPosition)
setPosition(parentItem, pos);
pos = parent;
}
heap[pos] = item;
if (setPosition !== undefined)
if (hasSetPosition)
setPosition(item, pos);
}