Transformations inside Array.prototype.sort()

Benchmark created on


Setup

function getRandomDate() {
    return new Date(new Date() - Math.random()*(1e+12))
}

function formatDate(date) {
  const day = date.getDate().toString().padStart(2, '0');
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const year = date.getFullYear().toString();
  return `${day}/${month}/${year}`;
}

function getRamdomDatesArray(arraySize) {
    let result = [];
    for(let i = 0; i < arraySize; i++ ) { result.push(getRandomDate()) }
    return result;
}

const randomDatesArr = getRamdomDatesArray(10000)

Test runner

Ready to run.

Testing in
TestOps/sec
Transform array elements in sort function
function sortWithTransformInside(arr) {
	return arr.sort( (a,b) => {
      let res = 0;
      if(new Date(formatDate(a)) < new Date(formatDate(b))){
        res = 1;
      } else if(new Date(formatDate(b)) < new Date(formatDate(a))) {
        res = -1;
      } 
      return res;
	})
}

sortWithTransformInside(randomDatesArr)
ready
Transform array elements before sort function
function sortWithTransformBefore(arr) {
	const transformedArr = arr.map( (item) => {
		return new Date(formatDate(item))
	})
	return transformedArr.sort( (a,b) => {
	  let res = 0;
      if(a < b){
        res = 1;
      } else if(b < a) {
        res = -1;
      } 
      return res;
	})
}

sortWithTransformBefore(randomDatesArr)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.