Created
October 8, 2021 04:24
-
-
Save eliannelavoie/3bfef9b355ec46e003415020def4f33d 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 { performance } = require('perf_hooks') | |
let iterations = 250; | |
let sizes = [10, 100, 1000, 1000000]; | |
let loopMethods = { | |
'while': iterWhile, | |
'for': iterFor, | |
'forEach': iterForEach, | |
'forOf': iterForOf | |
} | |
console.log('| # Elements | While | For | forEach() | For...of |'); | |
console.log('| - | - | - | - | - |'); | |
for (size of sizes) { | |
let line = `| ${size} |`; | |
for (const key in loopMethods) { | |
const method = loopMethods[key]; | |
let total = 0 | |
for (let i = 0; i < iterations; i++) { | |
let array = randomNumberArray(size); | |
let start = performance.now(); | |
method(array); | |
let end = performance.now(); | |
total += end - start; | |
} | |
line += ` ${(total / iterations).toPrecision(4)} |`; | |
} | |
console.log(line); | |
} | |
function iterWhile(array) { | |
let i = 0; | |
while (i < array.length) { | |
i++; | |
} | |
} | |
function iterFor(array) { | |
for (let i = 0; i < array.length; i++) { | |
} | |
} | |
function iterForEach(array) { | |
array.forEach((element) => { }); | |
} | |
function iterForOf(array) { | |
for (const element of array) { | |
} | |
} | |
function randomNumberArray(size) { | |
let array = new Array(size); | |
for (let i = 0; i < array.length; i++) { | |
array[i] = Math.random(); | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment