Exploring the capabilities of JavaScript's new array functions, I noticed significant differences in performance with the code snippets below. Check out the comparison on jsfiddle: http://jsfiddle.net/jKUm5/
Slowest for var i in array
(67.2ms):
for (var a=0;a<amount;a++) {
for (var b in arr) {
arr[b]++;
}
}
JS 5.1 array.forEach
(2.1ms):
for (var c=0;c<amount;c++) {
arr.forEach(function(e,i,a) {
arr[i]++;
});
}
Fastest (default)
(1.1ms):for var i=0;i<array.length;i++
for (var d=0;d<amount;d++) {
for (var e=0;e<arr.length;e++) {
arr[e]++;
}
}
Initially, I believed using for var i in array
was good practice compared to the default method, but it turns out the default is actually faster!
Here are my main questions:
- What causes the poor performance of
for var i in array
? - Why do we need another iterator method when we already have the default iterators?