const shuffleArray = array => {
const arr = [array];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
var testArr = Array.from({
length: 5000
}, () => Math.floor(Math.random() * 4000));
var scrambled = shuffleArray(testArr);
scrambled.sort((a,b) => testArr.findIndex(t => t === a) - testArr.findIndex(t => t === b));
testArr.map((t) => scrambled.find(s => s === t));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.sort + Array.findIndex | |
Array.map + Array.find |
Test name | Executions per second |
---|---|
Array.sort + Array.findIndex | 223.0 Ops/sec |
Array.map + Array.find | 303.0 Ops/sec |
Let's dive into explaining the provided benchmark.
Benchmark Definition JSON
The benchmark is designed to compare two approaches: using Array.sort
with Array.findIndex
, and using Array.map
with Array.find
. The benchmark aims to sort an array according to the sort order of another array.
Approach 1: Array.sort + Array.findIndex
This approach uses Array.sort()
method to sort the first array (scrambled
) based on the indices of elements in a second array (testArr
). The Array.findIndex()
method is used to find the index of an element in testArr
.
Pros:
Array.sort()
.Cons:
Array.findIndex()
introduces additional overhead due to the search operation.Approach 2: Array.map + Array.find
This approach uses Array.map()
method to create a new array with transformed values, where each element is found in testArr
using the Array.find()
method. The callback function takes an element from scrambled
as input and returns the corresponding index in testArr
.
Pros:
Array.findIndex()
, reducing search overhead.Cons:
Library: shuffleArray
The shuffleArray
function is used to scramble the elements of testArr
. This library is likely implemented using a Fisher-Yates shuffle algorithm, which is an efficient and unbiased shuffling method. The purpose of this library is to create a randomized version of testArr
for the benchmark.
Special JS Feature: None
Neither of the approaches relies on any special JavaScript features or syntax that would impact the understanding of the explanation.
Other Alternatives
Some alternative approaches could be:
Array.prototype.sort()
with a custom comparison function.Keep in mind that these alternatives may not provide a direct comparison to the original approaches, and their performance characteristics may differ.