Last active
June 2, 2022 04:05
-
-
Save neos1803/740cfd6f1f6e9751c6c1c62af33ca86a to your computer and use it in GitHub Desktop.
Javascript for loop iteration notes
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 array = [1,2,3,4,5,6,7,8]; | |
// Declarative looping example | |
array.forEach((x) => someFunction()); | |
array.map((x) => someFunction()); | |
array.reduce((x) => someFunction()); | |
// Imperative looping | |
for (const a of array) { | |
someFunction(); | |
} | |
for (let i = 0; i < array.length; i++) { | |
someFunction(); | |
} | |
const len = array.length; | |
for (let i = 0; i < len; i++) { | |
someFunction(); | |
} | |
/* | |
* Referenced from https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/#arrayforeach-vs-for-and-forof | |
* Looping using the declarative way is much slower than using the imperative way | |
* For ... of loop and classic for loop have roughly same performance for arrays | |
* Classic for can be expande to use temp element in it, but it doesn't have significance effect on performance | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment