var arr1 = [];
for(let i = 0; i < 10000; i++) {
arr1.push(Math.floor(Math.random() * 5000));
}
var arr2 = arr1.slice(0);
arr2.sort((a, b) => a - b);
var toSort = arr1.slice(0);
toSort.sort((a, b) => a - b);
var toSort = arr2.slice(0);
let lastEntry;
let isSorted = true;
for(const entry of toSort) {
if(lastEntry != null && entry < lastEntry) {
isSorted = false;
break;
}
lastEntry = entry;
}
if(!isSorted) {
toSort.sort((a, b) => a - b);
}
var toSort = arr2.slice(0);
toSort.sort((a, b) => a - b);
var toSort = arr1.slice(0);
let lastEntry;
let isSorted = true;
for(const entry of toSort) {
if(lastEntry != null && entry < lastEntry) {
isSorted = false;
break;
}
lastEntry = entry;
}
if(!isSorted) {
toSort.sort((a, b) => a - b);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Unsorted | |
Sorted with check | |
Sorted without check | |
Unsorted with check |
Test name | Executions per second |
---|---|
Unsorted | 216.2 Ops/sec |
Sorted with check | 23828.3 Ops/sec |
Sorted without check | 2419.5 Ops/sec |
Unsorted with check | 175.0 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Definition
The benchmark measures the performance of three different approaches for sorting an array:
Options Compared
The benchmark compares the performance of three different approaches:
Pros and Cons
Here are some pros and cons of each approach:
Library and Special JS Features
In this benchmark, no libraries are used. However, JavaScript does have some special features that can impact performance:
sort()
, forEach()
, and slice()
can be optimized by the V8 engine, but may still incur some overhead.Alternatives
Other approaches that could be compared in this benchmark include:
Overall, the benchmark provides a simple and straightforward way to compare the performance of three different approaches for sorting arrays.