Skip to content

Instantly share code, notes, and snippets.

@kevinchappell
Last active February 27, 2019 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinchappell/d514bab9b420c1400a43258f5a116e31 to your computer and use it in GitHub Desktop.
Save kevinchappell/d514bab9b420c1400a43258f5a116e31 to your computer and use it in GitHub Desktop.
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