Run details:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Chrome 63
Mac OS X 10.13.1
Other
2025 years ago
Test name Executions per second
PR Code 33171.7 Ops/sec
Comparison Code 87585.5 Ops/sec
Comparison Code 2, simple sort function 370951.2 Ops/sec
Script Preparation code:
x
 
var sortDirections = {
  DEFAULT: -1,
  ASC: 1,
  DESC: -1,
};
var numberArrayToSort = [1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7, 1, 4, 3, 2, 5, 6, 9, 10, 5, 8, 7];
// ---------------------------------
var compare = (lessThan, equalTo) => {
  if (equalTo) {
    return 0;
  }
  if (lessThan) {
    return -1;
  }
  return 1;
};
var compareStraight = (a, b) => {
  if (a === b) {
    return 0;
  }
  if (a < b) {
    return -1;
  }
  return 1;
};
var compareStraightNumber = (a, b) => a - b;
// ---------------------------------
var primitiveTypeComparator = (a, b) => compare(a < b, a === b);
var genericDirectionComparator = (comparator = primitiveTypeComparator) => (a, b, direction = sortDirections.ASC) => {
  return direction * comparator(a, b);
};
var sortByNumberComparator = genericDirectionComparator();
// ---------------------------------
var sortDirectionWrapper = (compareFunc, direction = sortDirections.ASC) => (a, b) => compareFunc(a, b) * direction;
var cleanStraightSort = (direction) => sortDirectionWrapper(compareStraight, direction);
var cleanStraightSortFast = (direction) => sortDirectionWrapper(compareStraightNumber, direction);
// ---------------------------------
Tests:
  • PR Code

     
    numberArrayToSort.sort((a, b) => sortByNumberComparator(a, b, sortDirections.ASC));
  • Comparison Code

     
    numberArrayToSort.sort(sortDirectionWrapper(primitiveTypeComparator, sortDirections.ASC));
  • Comparison Code 2, simple sort function

     
    numberArrayToSort.sort(sortDirectionWrapper(compareStraight, sortDirections.ASC));
  • Comparison Code 3, syntactic sugar

     
    numberArrayToSort.sort(cleanStraightSort(sortDirections.ASC))
  • Comparison Code 4, now even quicker?

     
    numberArrayToSort.sort(cleanStraightSortFast(sortDirections.ASC))