Loops

JavaScript performance comparison

Revision 181 of this test case created by TigerC10

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
  var arr = new Array(100);
  for(var i=99; i>=0; --i) {
    arr[i] = i+1;
  }
  arr = _.shuffle(arr);
  var sum = 0;
</script>
      
<script>
Benchmark.prototype.setup = function() {
  sum = 0;

};
</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
jQuery.each implementation
$.each(arr, function(index, value) {
  sum += value;
});
pending…
LoDash forEach implementation
_(arr).forEach(function(value) {
  sum += value;
});
pending…
angular.forEach implementation
angular.forEach(arr, function(value, index) {
  sum += value;
});
pending…
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
  sum += arr[i];
  ++i;
};
pending…
while loop that imitates a for loop, caching the length
var i = 0,
  len = arr.length;
while (i < len) {
  sum += arr[i];
  ++i;
};
pending…
Reverse while loop
var i = arr.length;
while (i--) {
  sum += arr[i];
};
pending…
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
  sum += arr[i];
};
pending…
Reverse do … while loop
var i = arr.length;
do {
  sum += arr[i];
} while (i--);
pending…
Reverse for loop
for (var i = arr.length; i--;) {
  sum += arr[i];
};
pending…
Standard for loop
for (var i = 0; i < arr.length; ++i) {
  sum += arr[i];
};
pending…
Standard for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
  sum += arr[i];
};
pending…
Standard for loop, noop in the iteration increment statement
for (var i = -1; ++i < arr.length;) {
  sum += arr[i];
};
pending…
Standard for loop, caching the length, noop in the iteration increment statement
for (var i = -1, len = arr.length; ++i < len;) {
  sum += arr[i];
};
pending…
Native Array#forEach implementation
arr.forEach(function(value, index) {
  sum += value;
});
pending…
Native Array#forEach implementation with named function
function foo(value, index) {
  sum += value;
};
arr.forEach(foo);
pending…
for var in implementation
for (var i in arr) {
  sum += arr[i];
}
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