Currently, let's talk about looping in JavaScript! As we all know that there several methods to do...
Currently, let's talk about looping in JavaScript! As we all know that there several methods to do it. Some of the methods that developers usually use are:
Developers love using Array.forEach
because it's simple and easy to use. But, have you ever wondered why we have so many options for looping? Why not just get rid of the rest and stick with the best one?
Here are the test cases and loops used for benchmarking.
Test Case
const iterations = ITERATION_TOTAL // 10, 100, 10000, 1000000, 10000000
const myArray = Array.from(Array(iterations).keys())
let total = 0
const start = performance.now()
// Looping method will be here
const end = performance.now()
console.log(`It took ${end - start} ms.`);
for (let i = 0; i < myArray.length; i++) {
total += myArray[i]
}
let i = 0
while (i < myArray.length) {
total += myArray[i]
i++
}
for (const item of myArray) {
total += item
}
myArray.forEach((item) => {
total += item
})
The tests were run with Node Js v18.17.0 . Each loop was tested for different iterations: 10, 100, 10,000, 1,000,000, and 10,000,000. I averaged the times I got for each iteration.
Here are the results for each loop with those iterations (the lower the better):
10 Iterations
100 Iterations
10,000 Iterations
1,000,000 Iterations
10,000,000 Iterations
It's all good to use any of the loop methods ( for
, while
, for...of
, and Array.forEach
) because most websites don't usually show more than 10,000 items on a page.
But when it comes to Backend Processing, Code Validation, Linting, etc., for
and while
loops are still totally the way to go! ????
So, not everything that's cool and easy on the developer side is the best for the project. There might be some trade-offs, you know. ✨