Multi Column Sort

JavaScript performance comparison

Test case created by agershun

Info

Compare multi-column sort functions

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var a = [];
    for (var i = 0; i < 100000; i++) {
      a.push({
        one: i,
        two: i * i * i % 19,
        three: i * i % 13
      });
    };
   
    // Function
   
    function multiColumnSort(arr, sf) {
      var s = '';
      sf.forEach(function(f, idx) {
        s += 'if(arguments[0].' + f + '>arguments[1].' + f + ')return 1;';
        s += 'else if(arguments[0].' + f + '==arguments[1].' + f + ')';
        s += (idx < sf.length - 1) ? '{' : 'return 0';
      });
      s += Array(sf.length).join('}') + ';return -1';
      return arr.sort(new Function(s));
    };
   
    // Second case function  
    // http://stackoverflow.com/questions/11379361/how-to-sort-an-array-of-objects-with-multiple-field-values-in-javascript/21837811#21837811
   
    function dynamicSort(property) {
      return function(obj1, obj2) {
        return obj1[property] > obj2[property] ? 1 : obj1[property] < obj2[property] ? -1 : 0;
      }
    }
   
    function dynamicSortMultiple() {
      /*
       * save the arguments object as it will be overwritten
       * note that arguments object is an array-like object
       * consisting of the names of the properties to sort by
       */

      var props = arguments;
      return function(obj1, obj2) {
        var i = 0,
          result = 0,
          numberOfProperties = props.length;
        /* try getting a different result from 0 (equal)
         * as long as we have extra properties to compare
         */

        while (result === 0 && i < numberOfProperties) {
          result = dynamicSort(props[i])(obj1, obj2);
          i++;
        }
        return result;
      }
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
lodash _.sortBy()
_.sortBy(a, ["three", "two", "one"]);
pending…
multiColumnSort()
multiColumnSort(a, ["three", "two", "one"]);
pending…
dynamicSort()
a.sort(dynamicSortMultiple("three", "two", "one"));
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment