Created
October 21, 2020 07:36
-
-
Save michelefenu/3eddb2059524726afbe37c06c0aa5a0d to your computer and use it in GitHub Desktop.
JavaScript Array vs for performance test
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
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