Skip to content

Instantly share code, notes, and snippets.

@freeall
Created October 29, 2020 07: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 freeall/72071143b3e31540111899b61e402318 to your computer and use it in GitHub Desktop.
Save freeall/72071143b3e31540111899b61e402318 to your computer and use it in GitHub Desktop.
const testLength = Number(process.argv[2] || 10000000)
console.log('Loop speed test')
console.log(`Initiating array with ${testLength} items`)
const arr = new Array(testLength).fill(1)
time(loopSimple)
time(loopForIn)
time(loopForOf)
time(forEach)
time(reduce)
time(loopSimple)
time(loopForIn)
time(loopForOf)
time(forEach)
time(reduce)
function time (f) {
const start = Date.now()
const value = f()
const end = Date.now()
if (value !== arr.length) throw new Error(`${f.name} does not work lols`)
console.log(`${f.name} took ${end - start} ms`)
}
function loopSimple () {
let res = 0
for (let i = 0; i < arr.length; i++) res += arr[i]
return res
}
function loopForIn () {
let res = 0
for (const i in arr) res += arr[i]
return res
}
function loopForOf () {
let res = 0
for (const val of arr) res += val
return res
}
function forEach () {
let res = 0
arr.forEach(val => res += val)
return res
}
function reduce () {
return arr.reduce((res, val) => res += val, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment