| 1 | const Benchmark = require('benny') |
| 2 | const { generateRandomIntegerArray } = require('./benchmark-utils') |
| 3 | |
| 4 | const testArray = generateRandomIntegerArray(10000) |
| 5 | |
| 6 | /** |
| 7 | * |
| 8 | * @param values |
| 9 | */ |
| 10 | function loopMax (values) { |
| 11 | let max = -Infinity |
| 12 | for (const value of values) { |
| 13 | if (value > max) max = value |
| 14 | } |
| 15 | return max |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * |
| 20 | * @param values |
| 21 | */ |
| 22 | function reduceTernaryMax (values) { |
| 23 | return values.reduce((a, b) => (a > b ? a : b), -Infinity) |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * |
| 28 | * @param values |
| 29 | */ |
| 30 | function reduceMathMax (values) { |
| 31 | return values.reduce((a, b) => Math.max(a, b), -Infinity) |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * |
| 36 | * @param values |
| 37 | */ |
| 38 | function sortMax (values) { |
| 39 | return values.sort((a, b) => b - a)[0] |
| 40 | } |
| 41 | |
| 42 | Benchmark.suite( |
| 43 | 'max', |
| 44 | Benchmark.add('Math.max', () => { |
| 45 | Math.max(...testArray) |
| 46 | }), |
| 47 | Benchmark.add('loopMax', () => { |
| 48 | loopMax(testArray) |
| 49 | }), |
| 50 | Benchmark.add('reduceTernaryMax', () => { |
| 51 | reduceTernaryMax(testArray) |
| 52 | }), |
| 53 | Benchmark.add('reduceMath.max', () => { |
| 54 | reduceMathMax(testArray) |
| 55 | }), |
| 56 | Benchmark.add('sortMax', () => { |
| 57 | sortMax(testArray) |
| 58 | }), |
| 59 | Benchmark.cycle(), |
| 60 | Benchmark.complete(), |
| 61 | Benchmark.save({ file: 'max', format: 'json', details: true }), |
| 62 | Benchmark.save({ file: 'max', format: 'chart.html', details: true }), |
| 63 | Benchmark.save({ file: 'max', format: 'table.html', details: true }) |
| 64 | ) |