Home  >  Article  >  Web Front-end  >  Summary of for loop performance optimization in JS

Summary of for loop performance optimization in JS

不言
不言Original
2018-08-02 15:10:582126browse

This article introduces to you a summary of for loop performance optimization in JS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We really use too many FOR loops, but have you paid attention to its optimized writing? Record:

1. The most common way of writing, there is nothing wrong with it

for (var i = 0; i < 10; i++) {    // do something...}

2. The number of loops is variable Situation

for (var i = 0; i < arr.length; i++) {    // do something...}

In fact, most people write this way. The disadvantage of this way of writing is that the array must be read every time it loops The length is not cost-effective

3. Optimized writing of variables

for (var i = 0, l = arr.length; i < l; i++) {    // do something...}

Store the length and then loop No need to read the length

4. The above 3 can also be written like this

var i = 0, l = arr.length;        
for (; i < l; i++) {    // do something...}

This is just 3 It's just a variation of, another way of writing, not optimization at all. Because there is no block-level scope, the effect is the same as 3

5. Optimized writing and upgraded version

for (var i = arr.length - 1; i >= 0; i--) {    // do something...}

Recommended writing method, which saves a variable based on the third method.

Recommended related articles:

How to convert vue.js images to Base64, upload images and preview

js thread case - to achieve randomness Speed ​​typewriter effect

The above is the detailed content of Summary of for loop performance optimization in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn