refactor: cleanup .gitignore
[poolifier.git] / benchmarks / worker-selection / round-robin.mjs
1 import Benchmark from 'benchmark'
2 import { LIST_FORMATTER } from '../benchmarks-utils.js'
3
4 function generateWorkersArray (numberOfWorkers) {
5 return [...Array(numberOfWorkers).keys()]
6 }
7
8 const workers = generateWorkersArray(60)
9
10 let nextWorkerIndex
11
12 function roundRobinTernaryOffByOne () {
13 nextWorkerIndex =
14 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
15 return workers[nextWorkerIndex]
16 }
17
18 function roundRobinTernaryWithNegation () {
19 nextWorkerIndex =
20 !nextWorkerIndex || workers.length - 1 === nextWorkerIndex
21 ? 0
22 : nextWorkerIndex + 1
23 return workers[nextWorkerIndex]
24 }
25
26 function roundRobinTernaryWithPreChoosing () {
27 const chosenWorker = workers[nextWorkerIndex]
28 nextWorkerIndex =
29 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
30 return chosenWorker
31 }
32
33 function roundRobinIncrementModulo () {
34 const chosenWorker = workers[nextWorkerIndex]
35 nextWorkerIndex++
36 nextWorkerIndex %= workers.length
37 return chosenWorker
38 }
39
40 new Benchmark.Suite('Round robin tasks distribution')
41 .add('Ternary off by one', () => {
42 nextWorkerIndex = 0
43 roundRobinTernaryOffByOne()
44 })
45 .add('Ternary with negation', () => {
46 nextWorkerIndex = 0
47 roundRobinTernaryWithNegation()
48 })
49 .add('Ternary with pre-choosing', () => {
50 nextWorkerIndex = 0
51 roundRobinTernaryWithPreChoosing()
52 })
53 .add('Increment+Modulo', () => {
54 nextWorkerIndex = 0
55 roundRobinIncrementModulo()
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()