Skip to content

Commit dbb6b40

Browse files
Uzlopakmcollina
authored andcommitted
perf: non-recursive implementation of euclidian gcd in balanced pool (#3461)
1 parent 405a2ce commit dbb6b40

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

lib/dispatcher/balanced-pool.js

+22-3
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,23 @@ const kWeight = Symbol('kWeight')
2525
const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
2626
const kErrorPenalty = Symbol('kErrorPenalty')
2727

28+
/**
29+
* Calculate the greatest common divisor of two numbers by
30+
* using the Euclidean algorithm.
31+
*
32+
* @param {number} a
33+
* @param {number} b
34+
* @returns {number}
35+
*/
2836
function getGreatestCommonDivisor (a, b) {
29-
if (b === 0) return a
30-
return getGreatestCommonDivisor(b, a % b)
37+
if (a === 0) return b
38+
39+
while (b !== 0) {
40+
const t = b
41+
b = a % b
42+
a = t
43+
}
44+
return a
3145
}
3246

3347
function defaultFactory (origin, opts) {
@@ -105,7 +119,12 @@ class BalancedPool extends PoolBase {
105119
}
106120

107121
_updateBalancedPoolStats () {
108-
this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
122+
let result = 0
123+
for (let i = 0; i < this[kClients].length; i++) {
124+
result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
125+
}
126+
127+
this[kGreatestCommonDivisor] = result
109128
}
110129

111130
removeUpstream (upstream) {

0 commit comments

Comments
 (0)