Performance for, foreach and for key I have a question about of the performance of using for loops (normal for, for each and for key in object) in JavaScript.

Just now I created this code to test:

var stopwatch = function(){
    var start;

    this.Start =function(){
        this.start = new Date().getTime();
    }

    this.getDifference= function(){
        return new Date().getTime() - this.start;
    }
}

var stopwatch = new stopwatch();
var length = 1000000;
var array = new Array(length);
for(var i = 0; i&lt;length; i++){
    array[i]=1;
};

stopwatch.Start();
for(var i = 0; i&lt;length; i++){
    array[i]+1;
};
var time = stopwatch.getDifference();
console.log("Time of normal for: "+time);
stopwatch.Start();
array.forEach(function(entry){
    entry+1;
});
time = stopwatch.getDifference();
console.log("Time of for each: "+time);
stopwatch.Start();
for(key in array){
    array[key]+1;
}
time = stopwatch.getDifference();
console.log("Time of for key in array: "+time);


The result is the following 

Time of normal for: 29
Time of for each: 151
Time of for key in array: 803


It seems like the normal for is faster than the others implementations.  Is it right?
Well, here's some tips:


Never use for-in for arrays. for-in runs through the array properties.

var a = [1,2,3]
a.foo = 'bar'; // arrays are still objects
for(var i in a){console.log(i)} // will run over foo

forEach though native, but AFAIK is still slow compared to while and for. Some say it suffers the same overhead of calling a function (activation records, stack, scope lookup etc.)
Consider async instead. By the looks of it, you want to loop through an array as fast as possible to avoid freezing the browser. You can go with WebWorkers, or Timers. Here's an example using setInterval. It's not as fast as loops, but you won't be seeing those "Unresponsive script" and "He's dead Jim!" warnings:

var i = 1000000;
var looper = setInterval(function(){
  /* do something */

  if(!--i) clearInterval(looper);
},0);