Created
October 29, 2020 07:24
-
-
Save freeall/72071143b3e31540111899b61e402318 to your computer and use it in GitHub Desktop.
This file contains 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
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