// Create an array of 100,000 numbers (0 - 99,999)
var arr = Array.from(Array(100000).keys());
// Knuth Shuffle Function
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Randomize Order
shuffle(arr);
var max = Math.max(arr);
var min = Math.max(arr);
arr = arr.sort(function(a, b) {
return a - b;
});
var max = arr[arr.length];
var min = arr[0];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.Min - Math.Max | |
Array.Sort |
Test name | Executions per second |
---|---|
Math.Min - Math.Max | 1289.6 Ops/sec |
Array.Sort | 388.1 Ops/sec |
Let's dive into the world of microbenchmarks!
Benchmark Definition
The benchmark measures the performance difference between two approaches: Math.Min-Max
and Array.Sort
. Both methods are used to find the minimum and maximum values in an array.
Options Compared
There are two options being compared:
Math.max()
function twice to find both the minimum and maximum values in the array.sort()
function with a custom comparator, which returns the difference between two elements (a - b
). After sorting, it finds the first element (minimum) and the last element (maximum).Pros and Cons
Math.Min-Max
Pros:
Cons:
Array.Sort
Pros:
Cons:
Other Considerations
Array.Sort
method is sensitive to the initial order of elements in the array. A different starting point can lead to different results.Library: Knuth Shuffle Function
The shuffle()
function used in the benchmark preparation code is a simple randomized shuffle algorithm that rearranges the elements of an array. Its purpose is to randomize the order of the elements, which is often necessary when running benchmarks or tests on arrays.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntaxes being used in this benchmark.
Alternatives
If you wanted to explore alternative approaches, here are a few options:
Array.prototype.reduce()
: Instead of sorting the array and then finding the minimum and maximum values, you could use Array.prototype.reduce()
with a custom callback function to find both values in a single pass.Array.prototype.every()
and Array.prototype.some()
: You could use these methods to check if all elements are greater than or equal to the minimum value and some element is less than or equal to the maximum value, respectively.Keep in mind that each alternative approach may introduce additional complexity, overhead, or assumptions about the input data.