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