• Which type of loop is fastest in JavaScript?
  • By Kushsavani
  • Translation from: The Gold Project
  • This article is permalink: github.com/xitu/gold-m…
  • Translator: Hoarfroster
  • Proofreader: Chorer, HumanBeing, user 1924214047173

Knowing which for loop or iterator is appropriate for our needs prevents us from making silly mistakes that affect the performance of our application.

JavaScript is the “evergreen tree” of Web development. Both JavaScript frameworks (Node.js, React, Angular, Vue, etc.) and native JavaScript have a huge fan base. Let’s talk about modern JavaScript. Looping has always been an important part of most programming languages, and modern JavaScript gives us many ways to iterate or loop values.

But the question is whether we really know which loop or iteration is best for our needs. The for loop has many variations, such as for, for (in reverse order), for… Of, forEach, for… In, for… Await. This article will focus on these.

Which cycle is faster?

The answer is: for.

The thing that surprised me the most was that when I tested it on my local computer, I had to accept that for (in reverse order) was the fastest of all for loops. Here’s an example of a loop through an array that contains more than a million elements.

Note: The accuracy of the console.time() result depends largely on the system configuration on which we ran the test. You can learn more about accuracy here.

const million = 1000000; const arr = Array(million); // Const arr = [...Array(million)] console.time('⏳'); // const arr = [...Array(million)] console.time('⏳'); for (let i = arr.length; i > 0; I --) {} // for(let I = 0; i < arr.length; ForEach (v => v) // forEach: -2.1 ms for (const v of arr) {} // for... The console of: 11.7 ms. TimeEnd (' ⏳ ');Copy the code

The reason for this is simple. In the code, the forward and reverse for loops take about the same amount of time, just 0.1 milliseconds off. The reason is that for (in reverse order) only evaluates the starting variable let I = arr.length once, whereas in a positive order for loop it checks the condition I

ForEach is a method of the Array prototype. In contrast to a normal for loop, forEach and for… Of takes more time to iterate through the array. (Note: But it’s worth noting that for… Both of and forEach get data from objects, whereas prototypes do not, so there is no comparison.)

The types of loops, and where we should use them

1. For loop (positive and reverse)

I think you’re probably familiar with this basic loop. We can use a for loop anywhere we want to run a piece of code as many times as we like. The basic for loop runs the fastest, so we should use it every time, right? No, performance is not the only yardstick. Code readability is often more important, so let’s choose the appropriate deformation for our application.

2. forEach

This method needs to take a callback function as an input parameter, iterate over each element of the array, and execute our callback function (given the element itself and its index (optional) as arguments to the callback function). ForEach also allows an 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); Have -0 fun-1 coding -2 */Copy the code

It is important to note that if we want to use forEach, we cannot use the JavaScript short-circuit operator (| |, &&…) That is, you cannot skip or end the loop every time.

3. The for... of

The for… Of was standardized in ES6 (ECMAScript 6). It creates a loop over an iterable object (such as array, map, set, string, etc.) and has the outstanding advantage of 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'}Copy the code

It is important to note that you do not use for in generators… Even for… The of cycle terminates prematurely. After exiting the loop, the generator is closed and attempts to iterate again without any further results.

4. for in

The for… In iterates the specified variable over all of the object’s enumerable properties. For each different property, for… The in statement returns the name of the user-defined attribute in addition to the numeric index. Therefore, it is best to use a traditional for loop with a numeric index when traversing a group of numbers. Because of the for… The in statement also iterates over user-defined attributes other than the group elements, even if we modify the array object (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
}
Copy the code

The for... ofThe for... in

The for… Of and the for… The main difference between ins is what they iterate over. The for… The in loop iterates over the properties of the object, while the for… The of loop iterates over the values of the iterable.

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'}Copy the code

conclusion

  • forFastest, but less readable
  • foreachIt’s faster, and it controls the content
  • for... ofIt’s slower, but it smells good
  • for... inIt’s slower. It’s not as convenient

Finally, a wise piece of advice — prioritize readability. This is especially necessary when developing complex structured programs. Of course, we should also focus on performance. Try to avoid adding unnecessary, redundant, fancy code, which can sometimes have a serious impact on the performance of your program. Have fun coding.

.

In the actual test of the translator, it is found that:

  • The results vary from browser to browser and even from version to version (upside down, e.g. Firefox doesn’t seem very friendly to native for-loop, Safari is extremely fond of while)
  • Depending on the platform operating system processor, the results will vary

If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.