Explain in detail which loop is the fastest in JavaScript

  • 2021-11-01 23:14:19
  • OfStack

Know which for loop or iterator is suitable for our needs, and prevent us from making some low-level errors that affect application performance.

JavaScript is an "evergreen tree" in the field of Web development. Both JavaScript frameworks (such as Node. js, React, Angular, Vue, etc.) and native JavaScript have a huge fan base. Let's talk about modern JavaScript. Loop 1 is an important part of most programming languages, and modern JavaScript provides us with many ways to iterate or loop values.
But the question is whether we really know which loop or iteration is best for our needs. There are many deformations in for cycle, such as for, for (reverse order), for … of, forEach, for … in, for … await. This article will focus on these discussions.

Which cycle is faster?

The answer is actually: for (reverse order)

What surprised me most was that after testing on the local computer, I had to accept the fact that for (reverse order) was the fastest of all for loops. I'll give you an example of a loop through an array that contains more than 1 million elements.
Disclaimer: The accuracy of console. time () results depends to a large extent on the system configuration on which we run the tests. You can take a step further to understand the accuracy here.


const million = 1000000; 
const arr = Array(million);

//  Note: This is a sparse array, and you should specify its contents, otherwise it will be handled differently by different loops: 
// const arr = [...Array(million)]

console.time('⏳');
for (let i = arr.length; i > 0; i--) {} // for( Reverse order ) :- 1.5ms
for (let i = 0; i < arr.length; i++) {} // for     :- 1.6ms
arr.forEach(v => v)           // foreach   :- 2.1ms
for (const v of arr) {}         // for...of   :- 11.7ms
console.timeEnd('⏳');

The reason for this is very simple. In the code, the forward and reverse for loops take almost one sample of time, only 0.1 millisecond apart. The reason is that for (reverse order) only needs to calculate the starting variable let i = arr. length once, whereas in the positive order for loop, it checks the condition i every time the variable is added < arr. length. This subtle difference is not very important, so you can ignore it. Translator's note: In the code with small amount of data or insensitive to time, we can ignore it, but according to the translator's test, when the amount of data increases, such as 1 billion, 100 billion, etc., the gap increases significantly, so we need to consider the impact of time on application performance.)
forEach is a method of Array prototype. Compared with ordinary for loop, forEach and for … of need to spend more time on array iteration. But it is worth noting that for … of and forEach both get data from objects, while prototypes don't, so there is no comparability.)

Types of loops and where we should use them

1. For cycle (positive and reverse order)

I think maybe everyone should be very familiar with this basic cycle. We can use the for loop wherever we need it, and run 1 piece of code as many times as we can. The most basic for loop runs the fastest, so we should use it every time, right? Otherwise, performance is not just a scale, and code readability is often more important, so let's choose the variant that suits our application.

2. forEach

This method takes a callback as an input argument, iterates through every element of the array, and executes our callback (given to the callback with the element itself and its index (optional argument) as arguments). forEach also allows one optional argument, this, to be used in the callback function.


const things = ['have', 'fun', 'coding'];
const callbackFun = (item, idex) => {
  console.log(`${item} - ${index}`);
}
things.foreach(callbackFun); 
/*  Output   have - 0
    fun - 1
    coding - 2 */

It should be noted that if we are using forEach, we cannot use the short-circuit operator of JavaScript, that is, we cannot skip or end the loop every time.

3. for … of

for … of is standardized in ES 6 (ECMAScript 6). It creates a loop for an iterable object (e.g. array, map, set, string, etc.) and has one outstanding advantage, excellent readability.


const arr = [3, 5, 7];
const str = 'hello';
for (let i of arr) {
  console.log(i); //  Output  3, 5, 7
}
for (let i of str) {
  console.log(i); //  Output  'h', 'e', 'l', 'l', 'o'
}

It is important to note that you do not use for … … of in the generator, even if the for … … of loop terminates prematurely. After exiting the loop, the generator is shut down and attempts to iterate again without producing any results that go one step further.

4. for in

for … in iterates over the specified variable on all enumerable properties of the object. For each different attribute, the for... in statement returns the name of the user-defined attribute in addition to the numeric index.

Therefore, it is best to use traditional for loops with numeric indexes when traversing arrays. Because the for... in statement also iterates over user-defined attributes other than array elements, even if we modify array objects (such as adding custom attributes or methods).


const details = {firstName: 'john', lastName: 'Doe'};
let fullName = '';
for (let i in details) {
  fullName += details[i] + ' '; // fullName: john doe
}

for … of and for … in

The main difference between for … of and for … in is the content of their iterations. for … in loops through the properties of objects, while for … of loops through the values of objects.


let arr= [4, 5, 6];
for (let i in arr) {
  console.log(i); // '0', '1', '2'
}
for (let i of arr) {
  console.log(i); // '4', '5', '6'
}

Conclusion

for is the fastest, but less readable foreach is fast and can control the content for... of is slower but fragrant for... in is slower and less convenient

Finally, give you a wise suggestion-give priority to readability. Especially when we develop complex structural programs, we need to do this. Of course, we should also focus on performance. Try to avoid adding unnecessary and redundant fancy code, because this may sometimes have a serious impact on your program performance. Have a good time coding.

Translator's note

In the translator's actual test, it is found that:

The results vary from browser to browser or even from version to version (upside down, for example, Firefox doesn't seem very friendly to native for-loop, and Safari extremely likes while) Different operating system processors on different platforms will have different results

Original address: Which type of loop is fastest in JavaScript?
Original author: kushsavani


Related articles: