Skip to content

Instantly share code, notes, and snippets.

@benjie
Last active Jun 4, 2021
Embed
What would you like to do?
Comparing loop method performance in JS
const arr = [];
const ARRAY_SIZE = parseInt(process.argv[2], 10) || 10;
const RUNS = Math.ceil(1000000000 / ARRAY_SIZE);
console.log(`Performing ${RUNS} runs of arrays with ${ARRAY_SIZE} elements`);
for (let i = 0; i < ARRAY_SIZE; i++) arr[i] = i;
function runTest(name, testFunction) {
if (global.gc) global.gc();
console.time(name);
let result;
for (let r = 0; r < RUNS; r++) {
result = testFunction();
}
console.timeEnd(name);
console.log(result);
}
for (let repeats = 0; repeats < 3; repeats++) {
runTest("for", function () {
let count = 0;
for (let i = 0, l = arr.length; i < l; i++) {
count += arr[i];
}
return count;
});
runTest("forOf", function () {
let count = 0;
for (const el of arr) {
count += el;
}
return count;
});
runTest("forEach", function () {
let count = 0;
arr.forEach((v) => {
count += v;
});
return count;
});
}

for loops still win.

For small loops over 3 items, for is only marginally faster after the warmup period:

$ node --expose-gc loop_perf.js 3
Performing 333333334 runs of arrays with 3 elements
for: 1.114s
3
forOf: 2.002s
3
forEach: 2.428s
3
for: 2.178s
3
forOf: 2.932s
3
forEach: 2.524s
3
for: 2.148s
3
forOf: 2.958s
3
forEach: 2.531s
3

For larger loops, over 100 items, for is a little faster:

$ node --expose-gc loop_perf.js 100
Performing 10000000 runs of arrays with 100 elements
for: 610.374ms
4950
forOf: 1.081s
4950
forEach: 881.132ms
4950
for: 585.957ms
4950
forOf: 1.070s
4950
forEach: 979.015ms
4950
for: 608.199ms
4950
forOf: 1.138s
4950
forEach: 1.088s
4950

For huge loops over one million items, for is over 10x faster:

$ node --expose-gc loop_perf.js 1000000
Performing 1000 runs of arrays with 1000000 elements
for: 712.047ms
499999500000
forOf: 844.897ms
499999500000
forEach: 11.852s
499999500000
for: 725.079ms
499999500000
forOf: 966.983ms
499999500000
forEach: 11.899s
499999500000
for: 719.693ms
499999500000
forOf: 967.394ms
499999500000
forEach: 12.117s
499999500000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment