From: Jérôme Benoit Date: Sat, 2 Sep 2023 21:40:18 +0000 (+0200) Subject: feat: add min benchmark X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=a6affe1656dc6a175c87eb5ad5ac4706243d56cf;p=benchmarks-js.git feat: add min benchmark Signed-off-by: Jérôme Benoit --- diff --git a/min.mjs b/min.mjs new file mode 100644 index 0000000..3ea46c4 --- /dev/null +++ b/min.mjs @@ -0,0 +1,71 @@ +import Benchmark from 'benny' +import { generateRandomNumberArray } from './benchmark-utils.mjs' + +const size = 10000 +const testArray = generateRandomNumberArray(size) + +/** + * + * @param values + * @returns + */ +function loopMin (values) { + let min = Infinity + for (const value of values) { + if (value < min) min = value + } + return min +} + +/** + * + * @param values + * @returns + */ +function reduceTernaryMin (values) { + return values.reduce((a, b) => (a < b ? a : b), Infinity) +} + +/** + * + * @param values + * @returns + */ +function reduceMathMin (values) { + return values.reduce((a, b) => Math.min(a, b), Infinity) +} + +/** + * + * @param values + * @returns + */ +function sortMin (values) { + return values.sort((a, b) => a - b)[0] +} + +Benchmark.suite( + `Min from ${size} numbers`, + Benchmark.add('Math.min', () => { + Math.min(...testArray) + }), + Benchmark.add('loopMin', () => { + loopMin(testArray) + }), + Benchmark.add('reduceTernaryMin', () => { + reduceTernaryMin(testArray) + }), + Benchmark.add('reduceMath.min', () => { + reduceMathMin(testArray) + }), + Benchmark.add('sortMin', () => { + sortMin(testArray) + }), + Benchmark.cycle(), + Benchmark.complete(), + Benchmark.save({ file: 'min', format: 'json', details: true }), + Benchmark.save({ file: 'min', format: 'chart.html', details: true }), + Benchmark.save({ file: 'min', format: 'table.html', details: true }) +).catch((err) => { + console.error(err) +}) diff --git a/package.json b/package.json index 4c1eb7a..0795c08 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "benchmark:is-undefined": "node is-undefined.mjs", "benchmark:quick-select": "node quick-select.mjs", "benchmark:max": "node max.mjs", + "benchmark:min": "node min.mjs", "benchmark:promise-handling": "node promise-handling.mjs", "benchmark:fibonacci": "node fibonacci.mjs", "benchmark:random": "node random.mjs",