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?
-
2\$\begingroup\$ You can check this link: jsperf.com/fastest-array-loops-in-javascript/24 \$\endgroup\$Benjamin RD– Benjamin RD2014年05月12日 17:50:58 +00:00Commented May 12, 2014 at 17:50
-
\$\begingroup\$ @MrMins thanks, that links was useful for me, so my code is ok? there is no other consideration to do with the code? And my result could be "real" and I could base my code practices in this little test? \$\endgroup\$rahpuser– rahpuser2014年05月12日 20:05:46 +00:00Commented May 12, 2014 at 20:05
1 Answer 1
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 towhile
andfor
. 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);
-
\$\begingroup\$ cool, that's why I was looking on faster implementations, I'm working with node.js and I trying to use the less webworkers possible. Thanks was a usuful answer. \$\endgroup\$rahpuser– rahpuser2014年05月14日 16:13:10 +00:00Commented May 14, 2014 at 16:13