optimizing-javascript-apps-loops.jpeg

Photo by Zachary Young on Unsplash


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.

There are two main factors that contribute to loop performance - work done per iteration and number of iterations.

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.