Compare different types of looping

JavaScript performance comparison

Test case created by Phil Glanville

Info

A quick comparison to prove that forEach is most definitely slower than a for loop, and that while(i--) is not faster either (for most browsers).

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var c = 0;
    var f = function(v){
      c += v;
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
forEach predefined
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0;
a.forEach(f);
pending…
forEach anon
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0;
a.forEach(function(v){
  c += v;
});
pending…
loop inc test
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0;
for(var i=0,l=a.length;i<l;i++){
  c += a[i];
};
pending…
loop dec test
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0; i = a.length;
while(--i){
  c += a[i];
};
pending…
loop w/ pop
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0;
while(v = a.pop()){
  c += v;
}
 
pending…
loop w/ shift
var a = [], b, v;
for(var i=0;i<500;i++){
  a.push(i);
};
c = 0;
while(v = a.shift()){
  c += v;
}
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