Merge dependabot/npm_and_yarn/examples/typescript/websocket-server-pool/ws-cluster...
[poolifier.git] / benchmarks / worker-selection / round-robin.mjs
CommitLineData
f1c674cd 1import Benchmark from 'benchmark'
d35e5717 2import { LIST_FORMATTER } from '../benchmarks-utils.cjs'
aacd8188 3
292ad316
JB
4function generateWorkersArray (numberOfWorkers) {
5 return [...Array(numberOfWorkers).keys()]
6}
aacd8188 7
292ad316 8const workers = generateWorkersArray(60)
aacd8188 9
e843b904 10let nextWorkerIndex
aacd8188 11
0d6f0c13 12function roundRobinTernaryOffByOne () {
aacd8188
S
13 nextWorkerIndex =
14 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
15 return workers[nextWorkerIndex]
16}
17
0d6f0c13 18function roundRobinTernaryWithNegation () {
472bf1f5
JB
19 nextWorkerIndex =
20 !nextWorkerIndex || workers.length - 1 === nextWorkerIndex
21 ? 0
22 : nextWorkerIndex + 1
23 return workers[nextWorkerIndex]
24}
25
0d6f0c13 26function roundRobinTernaryWithPreChoosing () {
aacd8188
S
27 const chosenWorker = workers[nextWorkerIndex]
28 nextWorkerIndex =
29 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
30 return chosenWorker
31}
32
0d6f0c13 33function roundRobinIncrementModulo () {
aacd8188
S
34 const chosenWorker = workers[nextWorkerIndex]
35 nextWorkerIndex++
36 nextWorkerIndex %= workers.length
37 return chosenWorker
38}
39
f1c674cd
JB
40new Benchmark.Suite('Round robin tasks distribution')
41 .add('Ternary off by one', () => {
aacd8188 42 nextWorkerIndex = 0
0d6f0c13 43 roundRobinTernaryOffByOne()
f1c674cd
JB
44 })
45 .add('Ternary with negation', () => {
472bf1f5 46 nextWorkerIndex = 0
0d6f0c13 47 roundRobinTernaryWithNegation()
f1c674cd
JB
48 })
49 .add('Ternary with pre-choosing', () => {
aacd8188 50 nextWorkerIndex = 0
0d6f0c13 51 roundRobinTernaryWithPreChoosing()
f1c674cd
JB
52 })
53 .add('Increment+Modulo', () => {
aacd8188 54 nextWorkerIndex = 0
0d6f0c13 55 roundRobinIncrementModulo()
f1c674cd
JB
56 })
57 .on('cycle', event => {
58 console.info(event.target.toString())
59 })
60 .on('complete', function () {
61 console.info(
62 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
63 )
64 })
65 .run()