function shuffle(array) {
for (let i = array.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function getRandomArray(size) {
const arr = Array(size).fill(0).map((el, i) => i);
shuffle(arr);
return arr;
}
var arr = getRandomArray(1e5);
var min = arr[0];
for (var i = 0; i < arr.length; i += 1) {
if (arr[i] < min) {
min = arr[i];
}
}
var min = Math.min(arr);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
Math.min |
Test name | Executions per second |
---|---|
For | 4378.9 Ops/sec |
Math.min | 269.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Definition: The benchmark definition is a JSON object that contains information about the benchmark being tested. In this case, it's comparing two approaches to find the minimum value in an array:
for
loop to iterate through the array and keep track of the minimum value.Math.min()
function, which is designed specifically for finding the minimum value in an iterable (such as an array).Options Compared: The benchmark is comparing two options:
Pros and Cons of Each Approach:
Math.min()
, requires manual initialization and updating of variables.Library Usage:
There is no library used in this benchmark. The Math.min()
function is a built-in part of the JavaScript language.
Special JS Features/Syntax: None are mentioned in the provided benchmark definition.
Other Alternatives: If you wanted to include other alternatives, some possible options could be:
Array.prototype.reduce()
method instead of a traditional loop.Array.prototype.forEach()
method with a callback function to iterate through the array.Keep in mind that these alternative approaches would depend on the specific requirements and use case, and may not necessarily provide better performance compared to the built-in Math.min()
function.