Loops

JavaScript performance comparison

Revision 291 of this test case created by Ludwig Stecher

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var arr = new Array(300).fill(Math.random());
  var out = new Array(300);

};

Benchmark.prototype.teardown = function() {
  if (out.length !== arr.length) {
    console.error("Test failed")
  }

};
</script>

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
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
 out.push(arr[i]);
}
pending…
Native Array#forEach implementation
arr.forEach(function(x) {
 out.push(x);
});
pending…
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
 out.push(arr[i]);
}
pending…
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
 out.push(arr[i]);
 i++;
}
pending…
Cool guy loop
for (var i = -1; ++i < arr.length;) {
 out.push(arr[i]);
}
pending…
Native Array#forEach implementation with named function
function foo(x) {
 out.push(x);
}
arr.forEach(foo);
pending…
Reverse for loop
for (var i = arr.length; i--;) {
 out.push(arr[i]);
}
pending…
Reverse do … while loop
var i = arr.length;
do {
 out.push(arr[i]);
} while (i--);
pending…
Reverse while loop
var i = arr.length;
while (i--) {
 out.push(arr[i]);
}
pending…
Native Array#forEach with closure
arr.forEach(x => out.push(x));
pending…
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
 out.push(arr[i]);
}
pending…
for of
for (const item of arr) {
 out.push(item);
}
pending…
Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
 out.push(arr[i]);
}
pending…
while loop that imitates a for loop, caching the length
var i = 0,
    len = arr.length;
while (i < len) {
 out.push(arr[i]);
 i++;
}
pending…

Revisions

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

0 Comments