Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

For Loop, While Loop, Do… While Loop and Other JavaScript Loops — Comparison and Performance

Five kinds of circulation

Loops play a crucial role in software development. They are used to iterate over sets of numbers or other iterable elements. In Javascript, we have several different types of loops. It can sometimes be confusing which loop we should use in a particular situation, and which loop is best in terms of performance. In this article, I’ll compare loops in Javascript, describe their strengths and weaknesses, and test the speed of each loop.

For loop and forEach() traversal

This is the most common loop in Javascript, and the most commonly used loop, which loops through a block of code a specified number of times. Let’s look at the code syntax for the for loop:

for (let i = 0; i <= 20; i++) {
  console.log (" www.duomly.com "); }Copy the code

It consists of three elements separated by a semicolon. First, we need to initialize the variables that start the loop using the initializer:

let i = 0;
Copy the code

The next element is the test condition, which checks how many times the code will be executed:

i <= 20
Copy the code

The final element is the updater, which is called at the end of each iteration to increase or decrease the loop’s counter. This loop is very flexible, we can run it at any point and we can stop it at any point, and it’s not that hard to understand. The downside of the for loop is that it doesn’t work for every type of data, and if you don’t understand it well, it’s easy to mess up.

Performance: Now let’s briefly test the speed of the for loop in different browsers. I’ll call the following code in Chrome, Safari, and Firefox to check the speed of the loop:

var counter = 1000;
var t0 = performance.now();
for (let i = 0; i < counter; i++) {
  console.log (" www.duomly.com "); }var t1 = performance.now();
consoleThe log (" For... Loop "+ (t1 -- t0) +" milliseconds. ");Copy the code

The test results

Chrome Firefox Safari
154.41 ms 243.56 ms 13 ms

In the case of the for loop, it is worth mentioning that it can be swapped using the forEach() array method. Let’s see how it works:

var array = [10.20.30.40];
array.forEach((item, index) = > { console.log(item) });
Copy the code

As you saw in the example above, the forEach() method also iterates over an array, but instead of specifying a condition or updater, we iterate over the given array and can return each item. Let’s examine the performance of this method:

var array = Array.from(Array(1000).keys(), n= > n + 1);
var t0 = performance.now();
array.forEach((item, index) = > { console.log (" www.duomly.com "); });var t1 = performance.now();
console(".log. ForEach () "+ (t1 - t0) +" milliseconds. ");Copy the code

The test results

Chrome Firefox Safari
156.41 ms 180 ms 12 ms

Based on our test results, we can see that the forEach method is faster in Firefox and Safari, but takes 3 milliseconds longer in Chrome.

The while loop

A while loop, very similar to a for loop, is used to repeat a block of code until the condition is false. When the while loop is executed, the condition is evaluated first, so if the condition is false on the first iteration, it is possible that the code block will not be invoked at all. Let’s look at the syntax of the while loop:

var counter = 20;
var i = 0;
while (i < counter) {
  console.log (" www.duomly.com "); i++ }Copy the code

The while loop also contains test conditions, code to execute, and updates. The main advantage of the while loop is that it can run for a long time until the condition is met, but on the other hand it’s easy to forget that if we don’t provide the condition (which will have false results) it will end up being an infinite loop, which will cause the application to freeze.

Performance: Let’s see how fast the while loop can be. I’ll test it again on Chrome, Firefox, and Safari based on the following code:

var counter = 1000;
var i = 0;
var t0 = performance.now();
while(i < counter) {
  console.log (" www.duomly.com "); i++; }var t1 = performance.now();
console.log (" While... Loop "+ (t1 -- t0) +" milliseconds. ");Copy the code

The test results

Chrome Firefox Safari
156.46 ms 243.60 ms 18 ms

do… The while loop

do… While is another loop that works in much the same way as the while loop, but with a difference, first executing the code block and then checking the condition. Let’s take a look at do… Syntax for the while loop:

var counter = 1000;
do {
  console.log (" www.duomly.com "); i++; }while (i < counter);
Copy the code

As you can see in the code snippet above, first we execute the code, which will run at least once before the first condition check. In do{}, we also have the updater, with a conditional test below. The biggest advantage of this loop is that you can execute the code at least once, even if the condition is already false.

Performance: Let’s test the speed of another popular Javascript loop. Again, I’ll test it on Chrome, Firefox, and Safari, with the following code:

var t0 = performance.now();
var counter = 1000;
var i = 0;
do {
  console.log (" www.duomly.com "); i++; }while (i < counter);
var t1 = performance.now();
consoleThe log (" the Do...whileLoop "+ (t1 -- t0) +" milliseconds. ");Copy the code

The test results

Chrome Firefox Safari
116.19 ms 189.71 ms 18 ms

for… In circulation

The for… The IN loop is another for loop in Javascript that allows you to iterate over object properties, with the code block executing once for each property. Let’s look at a code example:

var person = {
  name: Peter,age: 19.city: London,}for (let item in person) {
  console.log(‘key: ‘, item, ‘value: ‘, person[item]);
}
Copy the code

As you can see in the example, the number of times the code in the loop is called is the number of times we have properties in the object. There are no updaters and no conditional tests in this loop. The biggest advantage of this type of loop is that you can iterate over objects, which is not possible with other loops.

for… Of circulation

The for… The of loop, a new loop introduced in ES6, also allows iterating over iterable collections, which are objects with the [symbol.iterator] attribute. It can be used with arrays or strings. Let’s look at a code example:

varString = 'Duomly;for (let char of string) {
  console.log(char)
}
Copy the code

Performance overview

In this article, I tested the performance of three popular loops and an array method (for loop, while loop, do while loop, and forEach() method). I tested it with the same amount of execution in three different browsers. Now let’s take a look and summarize all the data we’ve got.

Loop type Time in ms
The for… cycle 154.41 ms
forEach() 156.41 ms
While… cycle 156.46 ms
The do… The while loop 116.19 ms

All loops were tested in Chrome. As can be seen from the table, do… The while loop is the fastest. The for loop was the second fastest, and the foreach() method seemed to be the slowest in the test environment.

conclusion

In this article, I described five different loops available in the Javascript programming language and tested the performance of three of them. The other two loops work differently, so comparisons are unreliable. The use of loops is very common in software development, but as developers, we need to remember the correct implementation and avoid nested loops because they have a negative impact on performance. Also, in a while loop, it’s important to note that the condition needs to be false at some point to avoid breaking the code. Be careful with your loops and have a good code.