Sort Array of Objects (v2)

Revision 2 of this benchmark created by bga_ on


Description

Was curious which of 2 cases was fastest. Seems it depends on the browser :) In general, data array would be an object of your making, and you would modify its prototype.toString();

Preparation HTML

<script>
  var random_objects = (function(n) {
   var objs = [];
  
   while (n--)
   objs[n] = {
    name: String.fromCharCode(Math.random() * 65000),
    value: Math.random()
   };
  
   return objs;
  })(1000);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Modifying toString() on object - return name
var _fn = Object.prototype.toString;

Object.prototype.toString = function() {
 return this.name;
};
random_objects.sort();

Object.prototype.toString = _fn;
ready
Pass in function to sort()
random_objects.sort(function(a, b) {
 if (a.name < b.name) {
  return -1;
 }

 if (a.name == b.name) {
  return 0;
 }

 if (a.name > b.name) {
  return 1;
 }
});
ready
Pass in function to sort() #2
random_objects.sort(function(a, b) {
 return 2 * (b.name > a.name) - 1
});
ready
Pass in function to sort() #3
random_objects.sort(function(a, b) {
 return b.value - a.value
});
ready

Revisions

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

  • Revision 1: published by meeech on
  • Revision 2: published by bga_ on