Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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