Moment.Diff vs. String Comparison

JavaScript performance comparison

Test case created by Carsten Wickner

Preparation code

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  var momentSort = function(list, dateFieldName) {
    return list.sort((a, b) =>
      moment(b[dateFieldName]).diff(moment(a[dateFieldName])));
  };
  var momentUtcSort = function(list, dateFieldName) {
    return list.sort((a, b) =>
      moment.utc(b[dateFieldName]).diff(moment.utc(a[dateFieldName])));
  };
  var lodashSort = function(list, dateFieldName) {
    return _.orderBy(list, [dateFieldName]);
  };
  
  var dateSort = function(list, dateFieldName) {
    return list.sort((a,b) => Date.parse(b[dateFieldName]) - Date.parse(a[dateFieldName]));
  };
  
  var randomDate = function (start, end) {
    return {
      date: new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).toString()
    };
  }
  var startDate = new Date(2017, 1, 1);
  var endDate = new Date(2017, 12, 31);
  var data = [
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate),
      randomDate(startDate, endDate)
  ];

};
</script>

Preparation code output

<script src="https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js"></script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Lodash OrderBy String
lodashSort(data, 'date')
pending…
Moment.js Diff
momentSort(data, 'date')
pending…
Moment.js Diff UTC
momentUtcSort(data, 'date')
pending…
Date Compare
dateSort(data, 'date')
pending…

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

0 Comments