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
}, () => ({val: Math.floor(Math.random() * 4000)}));
var scrambled = shuffleArray(testArr);
scrambled.sort((a,b) => a.val - b.val);
testArr.map((t) => t.val).map(t => ({val: t}));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.sort | |
Array.map |
Test name | Executions per second |
---|---|
Array.sort | 18063.5 Ops/sec |
Array.map | 27372.8 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
What is being tested?
The benchmark measures the performance of two different approaches to process an array of objects: Array.sort
and Array.map
.
Options compared
Two options are being compared:
Pros and cons of each approach:
Array.sort
:Array.map
:Array.sort
, especially for large datasets.Library used
The benchmark uses the shuffleArray
function to randomize the order of the elements in the test array. This library is not built-in to JavaScript; it's a custom implementation that ensures the array is properly shuffled before testing.
Special JS feature/syntax
None are mentioned explicitly in this benchmark, but it's worth noting that some modern browsers and JavaScript engines support features like const
and arrow functions (like () => { ... }
) for improved code readability and maintainability. However, these features do not affect the performance comparison being made.
Other alternatives
If you were to implement your own benchmarking tool, you might consider using other libraries or approaches, such as:
Array.prototype.sort()
and Array.prototype.map()
Array.sort
testKeep in mind that the specific alternatives will depend on your testing goals and requirements.