Measuring Performance of Different JavaScript Loop Types

Optimize your JavaScript code by using the right loop types.

Chameera Dulanga
Bits and Pieces

--

Image by Frank Winkler from Pixabay

As developers, we always push our limits to write better-performing applications. And most of the time, we look for performance from a higher level. But what about the tiny decisions you make in the code. Does it matter?

After thinking about it, I was curious to see how different Loops in JavaScript affects application performance as a starting point.

I hope you would also like to know the fastest Loop in JavaScript.

So, I went ahead with a small experiment to measure different types of Loops in JavaScript to measure their execution time.

Methods to Measure Performance

JavaScript has several inbuild functions that you can use to measure your code’s performance. Out of them, I’ve used Console.time and Console.timeEnd to measure as shown below.

console.time(‘Name’);//Your Code Goes Hereconsole.timeEnd(‘Name’);

Other than that, I have also considered Performance.now, Performance.mark and Performance.measure to measure execution time, but opted them out since console.time and console.timeEnd fits for the purpose.

Using Execution time as the Measurement

I have considered only the execution time since it’s the most dominant factor for most of our use cases since JavaScript is typically running in a single loop.

It’s also important to note that execution time is just one factor in measuring performance. Other factors, such as memory usage and consistency of execution, also matters.

Let’s look at a few scenarios where the impact is visible.

  • JavaScript server environments where we use NodeJS and process a large amount of data.
  • If you are using offline capabilities with the frontends and process data in Loops.
  • In resource-constrained environments (processing power, memory, battery) like mobile devices.

With NodeJS, the server code should execute reasonably fast to prevent the main thread from blocking. Otherwise, the subsequent requests will starve and be blocked. So if you are using any Loops, every second count at scale.

Now, let’s use these methods to measure the performance of different types of Loops in JavaScript.

Let's Compare the Performance of JS Loops

For the experiment, I have selected seven types of JavaScript Loops and used them to read an array with 100000 items and reassign them to a new Array.

I ran each of these Loops in both Chrome and Firefox browsers and used console.time to measure the performance.

You can also copy-paste these scripts in the Chrome console to test these for yourself.

  • for loop
var arr = new Array(100000).fill(Math.random());function testingFor(arr) {
console.time('for');
var res = [];
for (let i = 0; i < arr.length; i ++) {
res.push(arr[i]);
}
console.timeEnd('for')
return res;
}
testingFor(arr);

Chrome Output: 3ms
Firefox Output: 2ms

  • for/in loop
var arr = new Array(100000).fill(Math.random());function testingForIn(arr) {
console.time(‘for/in’);
var res = [];
for (var i in arr){
res.push(arr[i]);
}
console.timeEnd(‘for/in’)
return res;
}
testingForIn(arr);

Chrome Output: 18ms
Firefox Output: 12ms

  • for/of loop
var arr = new Array(100000).fill(Math.random());function testingForOf(arr) {
console.time(‘for/of’);
var res = [];
for (let i of arr){
res.push(i);
}
console.timeEnd(‘for/of’)
return res;
}
testingForOf(arr);

Chrome Output: 6ms
Firefox Output: 4ms

  • forEach()
var arr = new Array(100000).fill(Math.random());function testingForEach(arr) {
console.time(‘forEach’);
var res = [];
arr.forEach((value, index) => {
res.push(value);
});
console.timeEnd(‘forEach’)
return res;
}
testingForEach(arr);

Chrome Output: 4ms
Firefox Output: 2ms

  • map()
var arr = new Array(100000).fill(Math.random());function testingMap(arr) {
console.time(‘map’);
var res = arr.map(function(x){
return x;
});
console.timeEnd(‘map’)
return res;
}
testingMap(arr);

Chrome Output: 7ms
Firefox Output: 3ms

  • while loop
var arr = new Array(100000).fill(Math.random());function testingWhile(arr) {
console.time(‘While’);
var res = [];
x = arr.length;
i = 0;
while(i<x){
res.push(arr[i]);
i++;
}
console.timeEnd(‘While’);
return res;
}
testingWhile(arr);

Chrome Output: 6ms
Firefox Output: 37ms

  • do/while loop
var arr = new Array(100000).fill(Math.random());function testingDoWhile(arr) {
console.time(‘DoWhile’);
var res = [];
x = arr.length;
i = 0;
do{
res.push(arr[i]);
i++;
}while(i<x-1);
console.timeEnd(‘DoWhile’);
return res;
}
testingDoWhile(arr);

Chrome Output: 9ms
Firefox Output: 36ms

If you run these functions multiple times, you will notice that results change each time you run. That’s because browsers use countermeasures to avoid timing attacks. Besides, Operating System Scheduling and browser optimizations also account for these differences.

Tip: Share your reusable components between projects using Bit (Github).

Bit makes it simple to share, document, and reuse independent components between projects. Use it to maximize code reuse, keep a consistent design, speed delivery, and build apps that scale.

Bit supports Node, TypeScript, React, Vue, Angular, and more.

Exploring shared components on Bit.dev

Analyzing Will Give More Insights on Results

After going through the above results, you may question the differences between outputs in 2 browsers. The answer to that question is pretty straightforward, JavaScript engines of Chrome and Firefox are different from each other, and they use various optimization techniques.

Furthermore, let’s compare the results to see which loop has performed well.

Google Chrome — “for” is the Winner

Execution Times using Chrome Browser

In Google Chrome Browser, “for” Loop has shown the best performance with a minimum execution time while “for..in” showed the worst performance. The rest of the loops stays in the middle.

Firefox — “for”, “forEach”, “map” are joint Winners

Execution Times using Firefox Browser

When it comes to Firefox, “for”, forEach” and “map” Loops showed the best performances (the variation is minimal). “While” and “DoWhile” performed the worst. The rest of the loops stays in the middle.

Execution Times Chrome vs Firefox

When we compare the results across browsers, except “While” and “DoWhile” the variation is minimal. You can also see that the “for” or “forEach” are the best options for both browsers.

These results are equally applicable to NodeJS since it uses the V8 JavaScript engine under the hood, developed for Chrome.

Summary

If you are given the option to select a single Loop, use “for”, which has the least execution time.

And I would encourage you to minimize the use of “While”, “DoWhile” which might cause inconsistencies in your execution time across Chrome and Firefox.

And it’s also essential to decide your strategy based on balancing performance and maintainability. Therefore, if you prefer a more functional coding style, choosing “forEach” is a safer bet.

Besides, if your Arrays are smaller, these differences won’t make much of a difference.

Thank you for Reading!!!

--

--