Skip to content

Instantly share code, notes, and snippets.

@peter
Created May 7, 2021 12:21
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 peter/22fd12b305d98c6349bb0a6bbdfec22e to your computer and use it in GitHub Desktop.
Save peter/22fd12b305d98c6349bb0a6bbdfec22e to your computer and use it in GitHub Desktop.
javascript-loop-performance.js
#!/usr/bin/env node
// Figure out how performant different looping constructs in JavaScript are.
// Sample output:
// for-of: elapsed.stats={"min":26,"max":59,"avg":33.13} elapsed=26,26,27,28,29,30,30,30,30,30,30,30,30,30,31,31,31,31,31,31,31,31,31,31,31,31,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,35,35,35,35,35,35,35,35,36,36,36,36,36,36,36,37,38,40,47,59
// forEach: elapsed.stats={"min":34,"max":77,"avg":56.53} elapsed=34,52,52,52,52,53,53,53,53,53,53,53,53,53,53,53,53,53,54,54,54,54,54,54,54,54,54,54,54,54,54,54,54,54,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,57,57,57,57,57,57,57,57,57,57,58,58,58,58,59,59,59,59,59,60,60,61,61,63,63,65,67,69,70,70,72,73,77
// map: elapsed.stats={"min":38,"max":76,"avg":62.48} elapsed=38,58,58,58,58,58,58,58,58,58,58,58,58,58,59,59,59,59,59,59,59,59,59,59,59,59,59,60,60,60,60,60,60,60,60,60,61,61,61,61,61,61,61,61,62,62,62,62,62,62,62,62,62,63,63,63,63,63,63,63,63,63,63,63,63,63,64,64,64,64,64,64,64,64,64,65,65,65,65,66,66,66,66,66,66,67,67,67,67,69,69,69,70,71,71,71,72,73,73,76
const LIMIT = process.env.LIMIT || 1000000
const ITERATIONS = process.env.LIMIT || 100
const data = []
for (let i = 0; i < LIMIT; ++i) data.push(i)
function min (values) {
let result
for (const value of values) {
if (result === undefined || value < result) {
result = value
}
}
return result
}
function max (values) {
let result
for (const value of values) {
if (result === undefined || value > result) {
result = value
}
}
return result
}
function avg (values) {
return sum(values) / values.length
}
function sum (values) {
return values.reduce((acc, value) => acc + value, 0)
}
function stats (values) {
return {
min: min(values),
max: max(values),
avg: avg(values),
}
}
function logElapsed (name, fn) {
const allElapsed = []
for (let i = 0; i < ITERATIONS; i++) {
const startTime = new Date()
fn()
const elapsed = new Date() - startTime
allElapsed.push(elapsed)
}
console.log(`${name}: elapsed.stats=${JSON.stringify(stats(allElapsed))} elapsed=${allElapsed.sort()}`)
}
logElapsed('for-of', () => {
const newData = []
for (const i of data) {
newData.push(i * i)
}
})
logElapsed('forEach', () => {
const newData = []
data.forEach(i => {
newData.push(i * i)
})
})
logElapsed('map', () => {
const newData = []
data.map(i => {
newData.push(i * i)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment