feat: add min benchmark
[benchmarks-js.git] / min.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 loopMin (values) {
13 let min = Infinity
14 for (const value of values) {
15 if (value < min) min = value
16 }
17 return min
18 }
19
20 /**
21 *
22 * @param values
23 * @returns
24 */
25 function reduceTernaryMin (values) {
26 return values.reduce((a, b) => (a < b ? a : b), Infinity)
27 }
28
29 /**
30 *
31 * @param values
32 * @returns
33 */
34 function reduceMathMin (values) {
35 return values.reduce((a, b) => Math.min(a, b), Infinity)
36 }
37
38 /**
39 *
40 * @param values
41 * @returns
42 */
43 function sortMin (values) {
44 return values.sort((a, b) => a - b)[0]
45 }
46
47 Benchmark.suite(
48 `Min from ${size} numbers`,
49 Benchmark.add('Math.min', () => {
50 Math.min(...testArray)
51 }),
52 Benchmark.add('loopMin', () => {
53 loopMin(testArray)
54 }),
55 Benchmark.add('reduceTernaryMin', () => {
56 reduceTernaryMin(testArray)
57 }),
58 Benchmark.add('reduceMath.min', () => {
59 reduceMathMin(testArray)
60 }),
61 Benchmark.add('sortMin', () => {
62 sortMin(testArray)
63 }),
64 Benchmark.cycle(),
65 Benchmark.complete(),
66 Benchmark.save({ file: 'min', format: 'json', details: true }),
67 Benchmark.save({ file: 'min', format: 'chart.html', details: true }),
68 Benchmark.save({ file: 'min', format: 'table.html', details: true })
69 ).catch((err) => {
70 console.error(err)
71 })