Optimizing JavaScript Apps: Loops

Optimizing JavaScript Apps: Loops

One of the easiest and most ignored thing to do, in order to boost up the performance of our JavaScript applications, is to learn how to write properly high performant loop statements. The idea behind this article is to help with that.

One of the easiest and most ignored thing to do, in order to boost up the performance of our JavaScript applications, is to learn how to write properly high performant loop statements. The idea behind this article is to help with that.

We will see the main types of loop used in JavaScript and how can we write them in a performant way. Let's begin!

LOOP PERFORMANCE

When it comes to loop performance, the debate is always about which loop to use. Which is the fastest and most performant? The truth is, that, of the four loop types provided by JavaScript, only one of them is significantly slower than the others - for-in loop. The choice of loop type should be based on your requirements rather than performance concerns.

We will see the main types of loop used in JavaScript and how can we write them in a performant way. In the sections below we will see how by decreasing them, we can have a positive overall impact to the loop performance.

For Loop

ECMA-262, 3rd Edition, the specification that defines JavaScript's basic syntax and behavior, defines four types of loops. The first is the standard for loop, which shares its syntax with other C-like languages:

for (var i = 0; i < 10; i++){
    //loop body
}

This is probably the most commonly used JavaScript looping construct. In order to understand how can we optimize its work, we need to dissect it a little bit.

Dissection

The for loop consists of four parts: initialization, pretest condition, loop body, post-execute. The way it works is the following - first the initialization code is executed (var i = 0;), then the pretest condition (i < 10;). If the pretest condition evaluates to true, then the body of the loop is executed and after that the post-execute code (i++) is run.

Optimizations

The first step in optimizing the amount of work in a loop is to minimize the number of object member and array item lookups.

You can also increase the performance of loops by reversing their order. In JavaScript, reversing a loop does result in a small performance improvement for loops, provided that you eliminate extra operations as a result.

Both of the statements above are valid for the other two faster loops as well (while and do-while).

// original loop
for (var i = 0; i < items.length; i++){
    process(items[i]);
}

// minimizing property lookups
for (var i = 0, len = items.length; i < len; i++){
    process(items[i]);
}

// minimizing property lookups and reversing
for (var i = items.length; i--; ){
    process(items[i]);
}

While Loop

The second type of loop is the while loop. This is simple pretest loop, consisted of pretest condition and a loop body.

var i = 0;
while(i < 10){
    //loop body
    i++;
}

Dissection

If the pretest condition evaluates to true, the loop body is executed. If not - it's skipped. Every while loop can be replaced with for and vice versa.

Optimizations

// original loop
var j = 0;
while (j < items.length){
    process(items[j++]);
}

// minimizing property lookups
var j = 0,
    count = items.length;
while (j < count){
    process(items[j++]);
}

// minimizing property lookups and reversing
var j = items.length;
while (j--){
    process(items[j]);
}

Do-While Loop

do-while is the third type of loop and it's the only post-test loop in JavaScript. It is comprised of body loop and post-test condition:

var i = 0;
do {
    //loop body
} while (i++ < 10);

Dissection

In this type of loop, the loop body is executed always at least once, then the post-test condition is being evaluated, and if it's true, another loop cycle is executed.

Optimizations

// original loop
var k = 0;
do {
    process(items[k++]);
} while (k < items.length);

// minimizing property lookups
var k = 0,
    num = items.length;
do {
    process(items[k++]);
} while (k < num);

// minimizing property lookups and reversing
var k = items.length - 1;
do {
    process(items[k]);
} while (k--);

For-In Loop

The fourth and the last type of loop is called for-in loop. It has very special purpose - enumerates the named properties of any JavaScript object. Here it is how it looks like:

for (var prop in object){
    //loop body
}

Dissection

It's similar to the regular* for loop only by its name. The way it works is totally different. And this difference makes it much slower than the other three loops, which have equivalent performance characteristics such that it's not useful to try to determine which is fastest. Each time the loop is executed, the variable prop has the name of another property, which is a string*, on the object. It will execute until all properties have been returned. These would be the properties of the object itself, as well as the ones inherited through its prototype chain.

Notes

We will see the main types of loop used in JavaScript and how can we write them in a performant way. Each iteration through this loop causes a property lookup either on the instance or on the prototype, which makes the for-in loop much slower than the other loops. For the same number of iterations, it could be seven time slower than the rest.

Conclusion

👍 The for, while, and do-while loops all have similar performance characteristics, and so no one loop type is significantly faster or slower than the others.

👍 Avoid the for-in loop unless you need to iterate over a number of unknown object properties.

👍 The best ways to improve loop performance are to decrease the amount of work done per iteration and decrease the number of loop iterations.

I hope this was useful for you, as it was for me!

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.