Sorting dates benchmark

Benchmark created on


Setup

function generateObjectsWithDates(count) {
  count = count || 10000;
  var objects = [];
  var now = new Date();
  
  for (var i = 0; i < count; i++) {
    objects.push({
      id: i,
      date: new Date(now.getTime() - (i * 24 * 60 * 60 * 1000)),
      name: "Object " + i,
      value: Math.random() * 100
    });
  }
  
  return objects;
}

// Generate array of 10,000 objects with Date property
function generateObjectsWithDateStrings(count) {
  count = count || 10000;
  var objects = [];
  var now = new Date();
  
  for (var i = 0; i < count; i++) {
    var dateObj = new Date(now.getTime() - (i * 24 * 60 * 60 * 1000));
    objects.push({
      id: i,
      date: dateObj.toISOString(), // Convert to ISO string
      name: "Object " + i,
      value: Math.random() * 100
    });
  }
  
  return objects;
}

function sortFunction(a, b) {  
    var dateA = new Date(a.date).getTime();
    var dateB = new Date(b.date).getTime();
    return dateA > dateB ? 1 : -1;  
}

// Create the test data
var arrayWithDateProps = 
generateObjectsWithDates(10);

var arrayWithDateStringProps = generateObjectsWithDates(10);

function sortFunction(a, b) {  
    var dateA = new Date(a.date).getTime();
    var dateB = new Date(b.date).getTime();
    return dateA > dateB ? 1 : -1;  
}

Test runner

Ready to run.

Testing in
TestOps/sec
using sortFunction which creates new Date for each sort
arrayWithDateStringProps.sort(sortFunction);
ready
Using arrow sort which calls getTime of the date object to use for sorting
arrayWithDateProps.sort((a,b) => a.date.getTime() - b.date.getTime());
ready

Revisions

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