var array = [];
array.length = 10000;
array.fill(undefined);
array = array.map(() => Math.floor(Math.random() * array.length));
const set = new Set(array);
function findSet() {
for (let i = 0; i < array.length; i++)
if (!set.has(i)) return i;
return -1;
}
findSet();
const sortedArray = array.slice().sort((a, b) => a - b);
function findSort() {
for (let i = 0; i < array.length; i++)
if (!sortedArray.includes(i)) return i;
return -1;
}
findSort();
const sortedReduceArray = array.slice().sort((a, b) => a - b);
function findReduce() {
return sortedReduceArray.reduce((acc, current) => (Math.abs(current - acc) > 1 ? Math.min : Math.max)(current, acc), 0) + 1;
}
findReduce();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set With For Loop | |
Sort With For Loop | |
Sort With Reduce |
Test name | Executions per second |
---|---|
Set With For Loop | 4812.8 Ops/sec |
Sort With For Loop | 642.0 Ops/sec |
Sort With Reduce | 329.5 Ops/sec |
Let's break down the provided benchmarking setup and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Purpose
The main goal of this benchmark is to find the smallest number not present in an array. This problem can be useful for various scenarios, such as detecting missing values or finding the smallest gap in a sequence.
Test Cases
There are three test cases:
Set
data structure to store the indices of the array and then iterates through the original array using a for loop to find the first index not present in the set.Array.prototype.sort()
method and then iterates through the sorted array using a for loop to find the first index not present in the sorted array.Array.prototype.reduce()
method to find the smallest number by iterating through the sorted array and comparing each element with its predecessor.Comparison
The three approaches are compared based on their performance metrics, such as the time taken to execute the test case (measured in executions per second).
Pros/Cons of Each Approach:
Libraries and Special Features:
Array.prototype.sort()
method is used, which is a built-in JavaScript function.Array.prototype.reduce()
method is also used, which is another built-in JavaScript function.Alternative Approaches:
Other approaches to find the smallest missing number in an array include:
These alternative approaches may offer improved performance or efficiency for specific use cases, but they are not explored in this benchmark setup.