Last active
February 27, 2019 19:44
-
-
Save kevinchappell/d514bab9b420c1400a43258f5a116e31 to your computer and use it in GitHub Desktop.
Perforance test between for loop and reduce
This file contains hidden or 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 labels = Array.from({ length: 1000000 }, (v, k) => ({isVerified: Math.random() >= 0.6})) | |
function getAcceptedPercent1(labels) { | |
let acceptedCount = 0 | |
const total = labels.length | |
for (let index = 0; index < total; index++) { | |
acceptedCount += labels[index].isVerified | |
} | |
return Math.round(acceptedCount / total * 100) | |
} | |
function getPercentComplete2(labels) { | |
const verifiedCount = labels.reduce((acc, cur) => acc += cur.isVerified, 0) | |
return Math.round(verifiedCount / labels.length * 100) | |
} | |
// For Loop | |
const test1Start = performance.now() | |
console.log(getAcceptedPercent1(labels)) | |
const test1Stop = performance.now() | |
console.log(test1Stop - test1Start) | |
// Array.reduce | |
const test2Start = performance.now() | |
console.log(getPercentComplete2(labels)) | |
const test2Stop = performance.now() | |
console.log(test2Stop - test2Start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment