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