Which Type of Loop is fastest in JavaScript? In this paper, we compare the performance of four commonly used loop traversal methods in JavaScript, and summarize the application scenarios. The article is light on the ground, but it makes a useful point: code readability is important.

JavaScript plays an important role in Web development, whether it is NodeJS, React, Angular, Vue and other JavaScript frameworks or Vanilla JS. This is a meme that refers to native JavaScript) have a lot of fans. As an integral part of programming languages, JavaScript provides a variety of methods to support loop traversal, such as for, for(reverse), for… Of, for, for… In, for… Await. But the question is, how do we choose which of these looping methods best fits our needs? This is what this article will discuss.

What is the fastest looping method?

Answer: For (reverse)

On a PERSONAL computer, I tested these iterations and found that for(Reverse) was the fastest loop iteration. To test this, iterate through an array of 1 million elements and calculate the time it takes to complete the process, as follows:

const million = 1000000; 
const arr = Array(million);
console.time('⏳');

for (let i = arr.length; i > 0; i--) {} / / for (reverse) : 1.5 ms
for (let i = 0; i < arr.length; i++) {} / / for: 1.6 ms

arr.forEach(v= > v)                     / / foreach: 2.1 ms
for (const v of arr) {}                 // for... Of: 11.7 ms

console.timeEnd('⏳');
Copy the code

Here, the forward and reverse traversal time of FOR is almost the same, with only a difference of 0.1ms. The reason for this is that for(reverse) only lets I = arr.length once, whereas in for, I < arr.length is checked every time, and the slight difference can be ignored. In contrast to for, foreach and for… Of is more time consuming in array traversal.

For (let I = 0; i < arr.length; I ++) {} for (let I = 0, length = arr.length; i < length; I++) {} so is there no difference?

Application scenarios of different loop traversal methods

The for loop

For is a familiar loop traversal method, and its traversal speed is the fastest, so is it recommended to use for all scenarios? The answer is no, because in addition to performance considerations, readability of code is often more important.

forEach

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

o/p:- have - 0
      fun - 1
      coding - 2
Copy the code

ForEach cannot be terminated prematurely by a break or return during array traversal.

for … of

for… Of is a feature supported by ES6 for iterating over iterable objects such as String, Array, Map, and Set, which is more readable for code.

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

Airbnb’s code does not recommend using for… Of statement. If eslint is configured with eslint-config-airbnb, when code uses for… Iterators /generators require regenerator-Runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. While Airbnb’s code specification maintainers agree that code readability is more important than performance, for… The underlying iteration of of relies on Symbol, which needs to be supported by regenerator-Runtime. In order to use for… The cost of introducing an additional library is a bit high

for… in

for… In traverses all the enumerable properties of the accessed object. When used for… When accessing an array, in returns the array’s index as well as its user-defined properties, so avoid using for… In traverses the number group.

Translator’s note: To explain this problem, please refer to the following code

const array = ['k'.'o'.'o'];

array.koo = true;

for (const key in array) {
  console.log(key); // Print '0', '1', '2', 'koo'
}
Copy the code

Airbnb’s code specification also does not recommend the use of for… In to iterate through the properties of an Object. The recommended method is Object.{keys,values,entries}

conclusion

  • forThe fastest, but not very readable
  • foreachFast speed, controllable properties
  • for... ofIt’s slow, but it works
  • for... inIt’s slow, and it’s hard to use

One final piece of advice is to make your code readable first. When developing a complex structure (system), code readability is essential, but performance should also be a concern. Try to avoid adding unnecessary things to your code to minimize the impact on application performance.


Refer to the reading

  • Using ‘ForOfStatement’ is not allowed
  • Array iteration methods summarized
  • Airbnb JavaScript Style Guide

Follow public account