min max array search

JavaScript performance comparison

Revision 6 of this test case created by S.

Info

http://ejohn.org/blog/fast-javascript-maxmin/

Preparation code

<script src="//rawgithub.com/andrewplummer/Sugar/master/release/sugar.min.js">
</script>
<script>
var data = [];
for (var i = 0; i < 1000; i++) {
  data[i] = Math.random() * 1000;
};

var saved_array = [];
for (var i = 0; i < 1000; i++) {
  saved_array[i] = data[i];
};

var arraymax = function(array) {
 var l = array.length,
     max = array[0];
 
 while (--l) {
   if (array[l] > max) max = array[l];
 }
 
 return max;
}

function insertSort(arr) {
  for (var i = 1, l = arr.length; i < l; ++i) {
    var tmp = arr[i], j = i;
    while(arr[j-1] > tmp) {
      arr[j] = arr[j-1];
      --j;
    }
    arr[j] = tmp;
  }
  return arr;
}

var forMax = function(array) {
    var _t = array[0];
    for (var i = 0, l = array.length; i < l; i++) {
      _t = array[i] > _t ? array[i] : _t
    }
    return _t;
  }

var sortMax = function(array) {
  array.sort(function(a, b) {
    return a - b;
  });
  return array.pop();
}
</script>
<script>
Benchmark.prototype.setup = function() {
    for (var i = 0; i < 1000; i++) {
      data[i] = saved_array[i];
    };
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Math min/max apply()
var max = Math.max.apply( Math, data);
pending…
linear lookup
    
var max = arraymax(data);
pending…
Math min/max apply() null
var max = Math.max.apply( null, data);
pending…
Insert sort pop
var max = insertSort(data).pop();
pending…
sugar.js
var max = data.max();
pending…
for loop
var max = forMax(data);
pending…
sort Max
var max = sortMax(data);
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