Skip to content

Commit

Permalink
perf: non-recursive implementation of euclidian gcd in balanced pool (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak authored and mcollina committed Aug 17, 2024
1 parent 405a2ce commit dbb6b40
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions lib/dispatcher/balanced-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,23 @@ const kWeight = Symbol('kWeight')
const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
const kErrorPenalty = Symbol('kErrorPenalty')

/**
* Calculate the greatest common divisor of two numbers by
* using the Euclidean algorithm.
*
* @param {number} a
* @param {number} b
* @returns {number}
*/
function getGreatestCommonDivisor (a, b) {
if (b === 0) return a
return getGreatestCommonDivisor(b, a % b)
if (a === 0) return b

while (b !== 0) {
const t = b
b = a % b
a = t
}
return a
}

function defaultFactory (origin, opts) {
Expand Down Expand Up @@ -105,7 +119,12 @@ class BalancedPool extends PoolBase {
}

_updateBalancedPoolStats () {
this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
let result = 0
for (let i = 0; i < this[kClients].length; i++) {
result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
}

this[kGreatestCommonDivisor] = result
}

removeUpstream (upstream) {
Expand Down

0 comments on commit dbb6b40

Please sign in to comment.