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

Summary of for loop performance optimization in JS

不言
Release: 2018-08-02 15:10:58
Original
2144 people have browsed it

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...}
Copy after login

2. The number of loops is variable Situation

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

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...}
Copy after login

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...}
Copy after login

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...}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template