Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0
Firefox 104
Windows
Desktop
2 years ago
Test name Executions per second
Unsorted 833.8 Ops/sec
Sorted with check 4719.0 Ops/sec
Sorted without check 1774.8 Ops/sec
Unsorted with check 876.9 Ops/sec
Script Preparation code:
AخA
 
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);
Tests:
  • Unsorted

     
    var toSort = arr1.slice(0);
    toSort.sort((a, b) => a - b);
  • Sorted with check

     
    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);
    }
  • Sorted without check

     
    var toSort = arr2.slice(0);
    toSort.sort((a, b) => a - b);
  • Unsorted with check

     
    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);
    }