HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Performance for, foreach and for key

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andforperformanceforeachkey

Problem

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<length; i++){
    array[i]=1;
};

stopwatch.Start();
for(var i = 0; i<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?

Solution

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);

Code Snippets

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

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

Context

StackExchange Code Review Q#49549, answer score: 3

Revisions (0)

No revisions yet.