From aacd8188a9f2f915d5fa02a0db885d7f3211a996 Mon Sep 17 00:00:00 2001 From: Shinigami Date: Sun, 14 Feb 2021 08:12:25 +0100 Subject: [PATCH] Revert choose worker implementation (#148) --- benchmarks/choose-worker.js | 57 +++++++++++++++++++++++++++++++++++++ src/pools/abstract-pool.ts | 6 ++-- 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 benchmarks/choose-worker.js diff --git a/benchmarks/choose-worker.js b/benchmarks/choose-worker.js new file mode 100644 index 00000000..38e6fc7c --- /dev/null +++ b/benchmarks/choose-worker.js @@ -0,0 +1,57 @@ +const Benchmark = require('benchmark') + +const suite = new Benchmark.Suite() + +const LIST_FORMATTER = new Intl.ListFormat('en-US', { + style: 'long', + type: 'conjunction' +}) + +const workers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +let nextWorkerIndex = 0 + +function chooseWorkerTernary () { + nextWorkerIndex = + workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1 + return workers[nextWorkerIndex] +} + +function chooseWorkerIncrementModuloWithPreChoosing () { + const chosenWorker = workers[nextWorkerIndex] + nextWorkerIndex = + workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1 + return chosenWorker +} + +function chooseWorkerIncrementModulo () { + const chosenWorker = workers[nextWorkerIndex] + nextWorkerIndex++ + nextWorkerIndex %= workers.length + return chosenWorker +} + +suite + .add('Ternary', function () { + nextWorkerIndex = 0 + chooseWorkerTernary() + }) + .add('Increment+Modulo with PreChoosing', function () { + nextWorkerIndex = 0 + chooseWorkerIncrementModuloWithPreChoosing() + }) + .add('Increment+Modulo', function () { + nextWorkerIndex = 0 + chooseWorkerIncrementModulo() + }) + .on('cycle', function (event) { + console.log(event.target.toString()) + }) + .on('complete', function () { + console.log( + 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name')) + ) + // eslint-disable-next-line no-process-exit + process.exit() + }) + .run() diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index f6ed280c..ac3bd6cc 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -220,8 +220,10 @@ export abstract class AbstractPool< */ protected chooseWorker (): Worker { const chosenWorker = this.workers[this.nextWorkerIndex] - this.nextWorkerIndex++ - this.nextWorkerIndex %= this.workers.length + this.nextWorkerIndex = + this.workers.length - 1 === this.nextWorkerIndex + ? 0 + : this.nextWorkerIndex + 1 return chosenWorker } -- 2.34.1