There was a discussion in the chatroom about performance of JavaScript for
loops vs. map
. I was curious about how much difference there is, so tried timing them with this script. (Paste the code into a browser console to run it.)
I’m curious about what people think of the pros and cons of each approach. Even with 1 million items in the array, the difference is about 1/10 of a second on my computer. Also, let me know if there are better ways to test performance.
// for loop
function forLoop(arr) {
const output = [];
for (let i = 0; i < arr.length; i++) {
output.push(arr[i] * 2);
}
return output;
}
// map
function mapper(arr) {
return arr.map(n => n * 2);
}
// an array with a million numbers
const a = [...Array(1000000).keys()];
timeIt(forLoop, [a], 100);
timeIt(mapper, [a], 100);
function timeIt(func, args = [], times = 100) {
console.info(`please wait while function \`${func.name}\` runs ${times} times`);
// run the function `times` times
for (let i = 0; i < times; i++) {
performance.mark(`${func.name}-start`);
func(...args);
performance.mark(`${func.name}-end`);
performance.measure(`${func.name}-measures`, `${func.name}-start`, `${func.name}-end`);
}
const measures = performance.getEntriesByName(`${func.name}-measures`);
const avg = measures
.map(m => m.duration)
.reduce((acc, cur) => acc + cur) / measures.length;
console.log(`average speed when running function \`${func.name}\` ${times} times on ${a.length} items is ${avg} ms`);
performance.clearMarks();
performance.clearMeasures();
}
Update: when I run this code in Google Chrome or Chromium, map
is significantly slower. When I run the code in Firefox, the for
loop is almost twice as fast as in Chrome (though only about ~10 ms difference), and Firefox’s map
version runs just as fast as its for
loop version.