Loop Performance

JavaScript performance comparison

Revision 4 of this test case created by Roberto Huertas

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var arr = [];
  for (var i = 0; i < 10000; i++) {
    arr.push({
      Number: i
    });
  };
  var res = [];
  
  function Named(o, i) {
    res.push(arr[i]);
  };

};

Benchmark.prototype.teardown = function() {
  var e = res.length;
  arr = [];
  res = [];

};
</script>

Preparation code output

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
Normal For
for (var i = 0, len = arr.length; i < len; i++) {
  res.push(arr[i]);
};
pending…
Reversed For
for (var i = arr.length - 1; i >= 0; i--) {
  res.push(arr[i]);
};
pending…
While
var len = arr.length;
var i = 0;
while (i < len) {
  res.push(arr[i]);
  i++;
}
pending…
Post-Test
var len = arr.length;
var i = 0;
do {
  res.push(arr[i]);
  i++;
} while (i < len);
pending…
Post-Test reversed
var i = arr.length - 1;
do {
  res.push(arr[i]);
  i--;
} while (i >= 0);
pending…
Post-Test optimized
var i = arr.length - 1;

do {
  res.push(arr[i]);
} while (--i >= 0);
pending…
jQuery
$.each(arr, function(i, o) {
  res.push(o);
});
pending…
Underscore
_.each(arr, function(o, i) {
  res.push(o);
});
pending…
forEach
arr.forEach(function(o, i) {
  res.push(o);
});
pending…
forEach w Named Function
arr.forEach(Named);
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.

0 Comments