38e6fc7c5a4a772f50fb08f899173db7e3763b25
[poolifier.git] / benchmarks / choose-worker.js
1 const Benchmark = require('benchmark')
2
3 const suite = new Benchmark.Suite()
4
5 const LIST_FORMATTER = new Intl.ListFormat('en-US', {
6 style: 'long',
7 type: 'conjunction'
8 })
9
10 const workers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
11
12 let nextWorkerIndex = 0
13
14 function chooseWorkerTernary () {
15 nextWorkerIndex =
16 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
17 return workers[nextWorkerIndex]
18 }
19
20 function chooseWorkerIncrementModuloWithPreChoosing () {
21 const chosenWorker = workers[nextWorkerIndex]
22 nextWorkerIndex =
23 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
24 return chosenWorker
25 }
26
27 function chooseWorkerIncrementModulo () {
28 const chosenWorker = workers[nextWorkerIndex]
29 nextWorkerIndex++
30 nextWorkerIndex %= workers.length
31 return chosenWorker
32 }
33
34 suite
35 .add('Ternary', function () {
36 nextWorkerIndex = 0
37 chooseWorkerTernary()
38 })
39 .add('Increment+Modulo with PreChoosing', function () {
40 nextWorkerIndex = 0
41 chooseWorkerIncrementModuloWithPreChoosing()
42 })
43 .add('Increment+Modulo', function () {
44 nextWorkerIndex = 0
45 chooseWorkerIncrementModulo()
46 })
47 .on('cycle', function (event) {
48 console.log(event.target.toString())
49 })
50 .on('complete', function () {
51 console.log(
52 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
53 )
54 // eslint-disable-next-line no-process-exit
55 process.exit()
56 })
57 .run()