Commit | Line | Data |
---|---|---|
aacd8188 S |
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 | ||
472bf1f5 JB |
20 | function chooseWorkerTernaryWithNegation () { |
21 | nextWorkerIndex = | |
22 | !nextWorkerIndex || workers.length - 1 === nextWorkerIndex | |
23 | ? 0 | |
24 | : nextWorkerIndex + 1 | |
25 | return workers[nextWorkerIndex] | |
26 | } | |
27 | ||
28 | function chooseWorkerTernaryWithPreChoosing () { | |
aacd8188 S |
29 | const chosenWorker = workers[nextWorkerIndex] |
30 | nextWorkerIndex = | |
31 | workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1 | |
32 | return chosenWorker | |
33 | } | |
34 | ||
35 | function chooseWorkerIncrementModulo () { | |
36 | const chosenWorker = workers[nextWorkerIndex] | |
37 | nextWorkerIndex++ | |
38 | nextWorkerIndex %= workers.length | |
39 | return chosenWorker | |
40 | } | |
41 | ||
42 | suite | |
43 | .add('Ternary', function () { | |
44 | nextWorkerIndex = 0 | |
45 | chooseWorkerTernary() | |
46 | }) | |
472bf1f5 JB |
47 | .add('Ternary with negation', function () { |
48 | nextWorkerIndex = 0 | |
49 | chooseWorkerTernaryWithNegation() | |
50 | }) | |
51 | .add('Ternary with PreChoosing', function () { | |
aacd8188 | 52 | nextWorkerIndex = 0 |
472bf1f5 | 53 | chooseWorkerTernaryWithPreChoosing() |
aacd8188 S |
54 | }) |
55 | .add('Increment+Modulo', function () { | |
56 | nextWorkerIndex = 0 | |
57 | chooseWorkerIncrementModulo() | |
58 | }) | |
59 | .on('cycle', function (event) { | |
60 | console.log(event.target.toString()) | |
61 | }) | |
62 | .on('complete', function () { | |
63 | console.log( | |
64 | 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name')) | |
65 | ) | |
66 | // eslint-disable-next-line no-process-exit | |
67 | process.exit() | |
68 | }) | |
69 | .run() |