JavaScript loops profiled
Today I was curious and wanted to know which way of looping in JavaScript fastest. So far, I always use for var i in array, since someone once told me, it is the fastest way. For testing I created an Array with 10000 elements:
ids = [];
for (var i = 1; i <= 10000; i++) {
ids.push(i);
}
I used the JavaScript Profiler of Firebug for profiling. The testsystem was: Intel Dual Core T2500 @ 2.00 GHz, 2 GB RAM, Ubuntu 8.04, Firefox 3.0.5 (only installed addon is Firebug). I profiled each loop variation 5 times and took the average time for comparison. The loop variations did nothing but loop and were the following:
Loop 1:
for(var i = 0; i < ids.length; i++) {}
Loop 2:
for (var i in ids) {}
Loop 3:
function process(element, index, array) {}
ids.forEach(process);
When I started the test, I didn't think there would be such huge differences in the performance of those three:

Here are the profiling results in detail, in case you're interested (all times in ms):
Loop 1:
1,428
0,842
0,987
0,833
0,831
Loop 2:
6,084
4,471
6,040
6,256
6,509
Loop 3 (number in brackets is the profiled runtime of the function process() - see declaration above)
33,055 (16,439)
33,262 (16,489)
33,792 (17,044)
34,682 (17,312)
35,875 (17,637)
2 comments
Dominik Jungowski
20.01.2009, 13:37 o'clock
Main reason why I did this test, was to test whether forEach would be any useful in my case (iterating over an array of ids), since I just discovered it today :D I could have thought of it myself that it will probably be slower because of the callback, but you never know with JavaScript ;D
Thanks for the for… in comment btw, I always wondered why I sometimes have function in there when looping over it
20. Januar 2009
comments feed
recent posts
slink
20.01.2009, 13:00 o'clock
Since these methods are not equilant, it makes no sense to compare them. Keep in mind that the "for … in " statement returns all enumerable properties, hence you get the user defined methods of Array, too. The forEach way is nice, but it costs a lot because it has to run "i" times a function.