Created
May 9, 2022 19:07
-
-
Save cyborgx37/ef60edea792e632f93b6e1992d744cdc to your computer and use it in GitHub Desktop.
Performance test between forEach and for of
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
function runTest_ForEach(a, b) { | |
const start = performance.now(); | |
a.forEach(v => { | |
b.push(v * 2); | |
}); | |
return performance.now() - start; | |
} | |
function runTest_ForOf(a, b) { | |
const start = performance.now(); | |
for (const v of a) { | |
b.push(v * 2); | |
} | |
return performance.now() - start; | |
} | |
console.log("Creating Array"); | |
const a = []; | |
for (let i = 0; i < 10000000; i++) { | |
a.push( Math.random() ); | |
} | |
const testRuns = 50; | |
const p25 = testRuns / 4; | |
const p50 = testRuns / 2; | |
const p75 = 3 * testRuns / 4; | |
const p100 = testRuns - 1; | |
let totalTime = 0; | |
console.log('Running For Each Tests'); | |
for (let i = 0; i < testRuns; i++) { | |
totalTime += runTest_ForEach(a, []); | |
if (i === 0) console.log('0%'); | |
if (i === p25) console.log('25%'); | |
if (i === p50) console.log('50%'); | |
if (i === p75) console.log('75%'); | |
if (i === p100) console.log('100%'); | |
} | |
console.log(`Average Time For Each: ${totalTime / 100}`); | |
totalTime = 0; | |
console.log('Running For Of Tests'); | |
for (let i = 0; i < testRuns; i++) { | |
totalTime += runTest_ForOf(a, []); | |
if (i === 0) console.log('0%'); | |
if (i === p25) console.log('25%'); | |
if (i === p50) console.log('50%'); | |
if (i === p75) console.log('75%'); | |
if (i === p100) console.log('100%'); | |
} | |
console.log(`Average Time For Of: ${totalTime / 100}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment