var array = [];
array.length = 10000;
array.fill(undefined);
array = array.map(() => Math.floor(Math.random() * array.length));
const set = new Set(array);
const maxSetValue = array.reduce(Math.max);
function findSet() {
for (let i = 0; i < maxSetValue; i++)
if (!set.has(i)) return i;
return -1;
}
findSet();
const sortedArray = array.slice().sort((a, b) => a - b);
const maxSortValue = sortedArray[array.length - 1];
function findSort() {
for (let i = 0; i < maxSortValue; 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 | 0.3 Ops/sec |
Sort With For Loop | 387.0 Ops/sec |
Sort With Reduce | 141.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The provided JSON represents a benchmark for finding the smallest number not in an array with dynamic maximum value. The script preparation code generates an array of 10,000 random numbers and fills it with undefined
values. This creates a unique scenario where the algorithm needs to find the smallest missing number within the range of the maximum value.
Options Compared
There are three approaches compared:
Set
data structure to keep track of numbers in the array. The function iterates through the array's length, checking if each number is present in the set. If not, it returns that number.reduce
method to find the smallest missing number. It sorts the array and then iterates through it, updating an accumulator with the minimum difference between the current number and the previous number.Pros and Cons
reduce
method.Libraries and Special Features
Other Considerations
When comparing these approaches, consider the following factors:
Alternative Approaches
Other approaches you might consider for this benchmark include:
However, keep in mind that these alternative approaches might have different time complexities, memory usage, or code readability requirements compared to the provided benchmark definition.
In conclusion, this benchmark provides an interesting comparison of three approaches for finding the smallest missing number in an array with dynamic maximum value. Understanding the pros and cons of each approach will help you choose the most suitable method for your specific use case.