Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Perforance test between for loop and reduce
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
You can’t perform that action at this time.