Skip to content

Instantly share code, notes, and snippets.

@michelefenu
Created October 21, 2020 07:36
Show Gist options
  • Save michelefenu/3eddb2059524726afbe37c06c0aa5a0d to your computer and use it in GitHub Desktop.
Save michelefenu/3eddb2059524726afbe37c06c0aa5a0d to your computer and use it in GitHub Desktop.
JavaScript Array vs for performance test
const numbers = [...Array(100000000).keys()]
const startTime = new Date()
// -- for
let result = 0
for (let i = 0; i < numbers.length; i++) {
const number = numbers[i]
if (number % 2 === 0) {
result = result + number * 2
}
}
//
const endTime = new Date()
const startTime2 = new Date()
// -- Array
const result2 = numbers
.filter(x => x % 2 === 0)
.map(x => x * 2)
.reduce((acc, x) => acc + x, 0)
// --
const endTime2 = new Date()
console.log('Result ', result, ' Time: ', endTime - startTime)
console.log('Result ', result2, ' Time: ', endTime2 - startTime2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment