From a6affe1656dc6a175c87eb5ad5ac4706243d56cf Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 2 Sep 2023 23:40:18 +0200 Subject: [PATCH] feat: add min benchmark MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- min.mjs | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 1 + 2 files changed, 72 insertions(+) create mode 100644 min.mjs 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", -- 2.34.1