Benchmarking 'for', 'while', 'for...of', and 'Array.forEach' - using Performance.now()

Muhammad A Faishal - Jul 19 '23 - - Dev Community

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?

Now, let's do some performance tests using Performance.now()!

Benchmarking

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.`);
Enter fullscreen mode Exit fullscreen mode

For

for (let i = 0; i < myArray.length; i++) {
  total += myArray[i]
}
Enter fullscreen mode Exit fullscreen mode

While

let i = 0

while (i < myArray.length) {
  total += myArray[i]
  i++
}
Enter fullscreen mode Exit fullscreen mode

For...of

for (const item of myArray) {
  total += item
}
Enter fullscreen mode Exit fullscreen mode

Array.forEach

myArray.forEach((item) => {
  total += item
})
Enter fullscreen mode Exit fullscreen mode

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.

Result

Here are the results for each loop with those iterations (the lower the better):

10 Iterations

Javascript loop 10 iterations

100 Iterations

Javascript loop 100 iterations

10,000 Iterations

Javascript loop 10000 iterations

1,000,000 Iterations

Javascript loop 1000000 iterations

10,000,000 Iterations

Javascript loop 10000000 iterations

Conclusion

For Frontend stuff, 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. ✨

. . . . . . . . . . .
Terabox Video Player