Last active
March 6, 2019 20:24
-
-
Save SidOfc/4d223c0e48dfb3f0fb798d2a6a57b44e to your computer and use it in GitHub Desktop.
A small benchmark of for vs forEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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