build: update volta pnpm version
[benchmarks-js.git] / max.mjs
1 import Benchmark from 'benny'
2 import { generateRandomNumberArray } from './benchmark-utils.mjs'
3
4 const size = 10000
5 const testArray = generateRandomNumberArray(size)
6
7 /**
8 *
9 * @param values
10 * @returns
11 */
12 function loopMax (values) {
13 let max = -Infinity
14 for (const value of values) {
15 if (value > max) max = value
16 }
17 return max
18 }
19
20 /**
21 *
22 * @param values
23 * @returns
24 */
25 function reduceTernaryMax (values) {
26 return values.reduce((a, b) => (a > b ? a : b), -Infinity)
27 }
28
29 /**
30 *
31 * @param values
32 * @returns
33 */
34 function reduceMathMax (values) {
35 return values.reduce((a, b) => Math.max(a, b), -Infinity)
36 }
37
38 /**
39 *
40 * @param values
41 * @returns
42 */
43 function sortMax (values) {
44 return values.sort((a, b) => b - a)[0]
45 }
46
47 Benchmark.suite(
48 `Max from ${size} numbers`,
49 Benchmark.add('Math.max', () => {
50 Math.max(...testArray)
51 }),
52 Benchmark.add('loopMax', () => {
53 loopMax(testArray)
54 }),
55 Benchmark.add('reduceTernaryMax', () => {
56 reduceTernaryMax(testArray)
57 }),
58 Benchmark.add('reduceMath.max', () => {
59 reduceMathMax(testArray)
60 }),
61 Benchmark.add('sortMax', () => {
62 sortMax(testArray)
63 }),
64 Benchmark.cycle(),
65 Benchmark.complete(),
66 Benchmark.save({ file: 'max', format: 'json', details: true }),
67 Benchmark.save({ file: 'max', format: 'chart.html', details: true }),
68 Benchmark.save({ file: 'max', format: 'table.html', details: true })
69 ).catch(err => {
70 console.error(err)
71 })