Skip to content

Instantly share code, notes, and snippets.

@Infocatcher
Created June 19, 2014 19:01
Show Gist options
  • Save Infocatcher/cd0975243a247bdf7ff5 to your computer and use it in GitHub Desktop.
Save Infocatcher/cd0975243a247bdf7ff5 to your computer and use it in GitHub Desktop.
Array iteration performance, replace performance.now() with Date.now() or new Date().getTime() in old browsers
var c = 20e3;
var arr = "abcdefghijklmnopqrstuvwxyz".split("");
var i = c + 1, t = performance.now();
while(--i) {
for(var j = 0, l = arr.length; j < l; ++j)
var v = arr[j];
}
var dtFor = performance.now() - t;
var i = c + 1, t = performance.now();
while(--i) {
arr.forEach(function(v, j) {});
}
var dtForEach = performance.now() - t;
var i = c + 1, t = performance.now();
while(--i) {
for(var [j, v] in Iterator(arr));
}
var dtIterator = performance.now() - t;
var i = c + 1, t = performance.now();
while(--i) {
for(var [j, v] of arr.entries()); // Firefox 28+
}
var dtExtries = performance.now() - t;
var i = c + 1, t = performance.now();
while(--i) {
for(var v of arr.entries()); // We don't have index here!
}
var dtForOf = performance.now() - t;
alert([
"classic for: " + dtFor .toFixed(2) + " ms",
"forEach(): " + dtForEach .toFixed(2) + " ms",
"Iterator(): " + dtIterator.toFixed(2) + " ms",
"entries(): " + dtExtries .toFixed(2) + " ms",
"for-of: " + dtForOf .toFixed(2) + " ms"
].join("\n"));
@Infocatcher
Copy link
Author

Interesting, Firefox 30 using Console²:

classic for: 16.00 ms
forEach(): 0.00 ms
Iterator(): 203.00 ms
entries(): 187.00 ms
for-of: 203.00 ms

With c = 100e3:

classic for: 16.00 ms
forEach(): 15.00 ms
Iterator(): 905.00 ms
entries(): 936.00 ms
for-of: 998.00 ms

(previously tested in Scratchpad)

@Infocatcher
Copy link
Author

Strange, http://jsperf.com/array-iteration-firefox

classic for  24,001,912 ±6.22%    fastest
forEach()    1,146,429 ±16.96%    96% slower
Iterator()   110,503 ±6.63%       100% slower
entries()    78,480 ±13.31%       100% slower
for-of       87,644 ±5.41%        100% slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment