Skip to content

Instantly share code, notes, and snippets.

@SidOfc
Last active March 6, 2019 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SidOfc/4d223c0e48dfb3f0fb798d2a6a57b44e to your computer and use it in GitHub Desktop.
Save SidOfc/4d223c0e48dfb3f0fb798d2a6a57b44e to your computer and use it in GitHub Desktop.
A small benchmark of for vs forEach
// run in terminal with: node woop-woop.js [arraySize = 1000000] [runs = 1]
// e.g. `node woop-woop.js 1000 2` runs the benchmark twice with thousand users.
const runs = parseInt(process.argv[3] || 1);
const arraySize = parseInt(process.argv[2] || 1000000);
let usersToGiveCoins = Array(arraySize).fill({username: 'Koala', coins: 0});
// simple benchmark function to wrap time + timeEnd and
// allows running benchmark an arbitrary number of times.
function bench(label, fn, times = 1) {
for (let i = 0; i < times; i++) {
console.time(`${label}#${i + 1}`);
fn();
console.timeEnd(`${label}#${i + 1}`);
}
}
console.log(`arraySize: ${arraySize}, runs: ${runs}`);
bench('forLoop', () => {
for (let i = 0; i < usersToGiveCoins.length; i++) {
usersToGiveCoins[i].coins += 5;
}
}, runs);
bench('forEach', () => usersToGiveCoins.forEach(user => user.coins += 5), runs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment