Exploration of javascript loop usage and Optimization

Source: Internet
Author: User

This article will introduce some performance optimization methods when using js event seeding loops. Below I will introduce some basic JS knowledge, it was found that the JS loop is significantly different from the loop in other languages, and then I continued to go through the authoritative tutorials of the two JSS and wrote this article.

We usually write a loop like this:

The Code is as follows: Copy code
Function (){
// General Circular Writing Method
For (var I = 0; I <values. length; I ++ ){
...
}
}
 

Optimization variable Declaration

The above method is correct when I first learned JavaScript, and is even correct for the vast majority of object-oriented languages. However, JavaScript is different from other object-oriented languages, he does not have block and scope, and some are just function scopes. Therefore, the above writing method is not very standard. In some cases, a Bug occurs. When you use a variable, then, if you declare it again in the function, a logical error may occur. For JavaScript, as long as your variable is in the same scope (the same function), it is declared, even when it is used before the var declaration. A reasonable statement is to declare the variable at the beginning of the function, rather than defining the variable within the loop.

The Code is as follows: Copy code
Function func (){
// Optimize the variable definition of JS. The variable definition is at the starting position to avoid block-level scope errors.
Var I;
For (I = 0; I <values. length; I ++ ){
...
}
}

Optimize dynamic set reading in a loop

After the JS loop variables are optimized, we continue to optimize them in depth. DOM is the most common issue in daily development. It is often the case of loop NodeList (if you do not know what a NodeList object is, review the basic knowledge ). All in all, it is similar to var divs = document. the divs of getElementsByTagName ("div") references the NodeList object. Other Similar NodeList relatives include NameNodeMap and HTMLCollection. When the structure of these three sets changes, they will all be updated (and dynamic updates ). This will lead to two problems. The first is the performance problem. Whenever you modify NodeList to read it, you will not read the previous NodeList but the modified and dynamically updated NodeList. Second, an infinite loop Bug occurs. For example, the following code causes an infinite loop:

 

The Code is as follows: Copy code
Function func (){
// Circular writing method that causes an infinite loop of NodeList
Var divs = document. getElementsByTagName ("div ");
For (var I = 0; I <divs. length; I ++ ){
Var div = document. createElement ("div ");
Document. body. appendChild (div );
Alert ("Infinite loop ");
}
}
Func ()

The circular code shown in the preceding example may cause a serious problem. length, which means that the query will get all div elements, and then create a new div element to add the document, so div. the length value increases progressively after each loop. Since I and divs. length increase at the same time, their values will never be equal, resulting in an infinite loop.

To avoid such inefficiency or even implicit Bug loop writing, the countermeasure is to minimize the number of times NodeList is accessed. Because every time you access NodeList, a document-based query is run. Therefore, you can consider caching the value obtained from NodeList. The following is the optimized statement:

The Code is as follows: Copy code
Function func (){
// Avoid the endless loop Writing Method of NodeList
Var divs = document. getElementsByTagName ("div ");
For (var I = 0, len = divs. length; I <len; I ++ ){
Var div = document. createElement ("div ");
Document. body. appendChild (div );
Alert ("Infinite loop will not happen ");
}
}
Func ()

It's easy. Just set divs. the length is cached in the len variable, so no matter how the NodeList changes, read is avoided to avoid infinite loops. Because of the interpretation of JavaScript,. b. c. d. e. You must perform at least four query operations. Check a first, then B in a, and then c in B. So if such expressions repeat, as long as possible, such expressions should appear as little as possible, and use local variables to put them in a temporary place for query. If div. length is queried each time, an additional operation is required. If var len = div. length is pre-queried, one query is missing, which greatly reflects the performance optimization. At first, you will feel that this writing method is not suitable, but you will soon get used to this "awkward" Writing Method After writing it several times.

Optimization continues optimization!

Replace I ++ with I + = 1

This is from the perspective of the essence of Javascript language. It generally means that when I ++ is used, there may be potential security problems. The ++ operator can be used before and after the operation to make the degree of freedom too large, if there is no semicolon at the end, it may lead to some errors, such as a ++ B ++ c. It is hard for you to understand what the previous Code means. According to the essence of Javascript language, this ++ or -- operator leads to poor code. Apart from the wrong architecture, they are the second biggest culprit that causes viruses and other security threats. Therefore, the JsLint option plusplus is used to check whether these operators are disabled. Another reason is that I + = 1 is more "native" than I ++ to improve performance, but I personally think that the readability is reduced, so choose between them as needed. Then our code will look like this again:

The Code is as follows: Copy code
Function func (){
// Impairment iteration optimization cycle
For (var I = values. length-1; I> = 0; I --){
...
}
}

Let the optimization be more intense!

Impairment iteration optimization cycle

Most cycles use an iterator that starts from 0 and increases to a specific value. In many cases, the iterator that continuously reduces the value in the cycle is more efficient from the maximum value. If the processing order of values is irrelevant, the cycle can be changed to I impairment. The optimization is as follows:

The Code is as follows: Copy code
Function func (){
// Loop optimization large series
Var I; // optimization variable Declaration
Var divs = document. getElementsByTagName ("div ");
For (I = divs. length-1; I> = 0; I-= 1) {// optimize the dynamic set reading, impairment iteration, and replace I with I-= 1 --
...
}
}

Loop optimization large series

If we put all the above loop optimization methods together, the writing method will be like this:

The Code is as follows: Copy code
12345678 function func () {// loop optimization large concatenation var I; // The optimization variable declaration var divs = document. getElementsByTagName ("div"); for (I = divs. length-1; I> = 0; I-= 1) {// optimize the dynamic set reading, impairment iteration, and replace I with I-= 1 --...}}

To be honest, the above loop Optimization of large series performance is improved, but the readability is also reduced to a new height. The code you write is cool and acceptable. As a team developer, the series above does not seem particularly desirable. I personally advocate partial optimization, to optimize performance and ensure readability:

The Code is as follows: Copy code

Function func (){
// Reasonable cyclic Optimization
Var I, len; // optimize variable Declaration
Var divs = document. getElementsByTagName ("div ");
For (I = 0, len = divs. length; I <len; I ++) {// read the dynamic set in the Optimized Loop. If necessary, replace I ++ with I ++ = 1.
...
}
}

I personally prefer the above JS loop. The rational Optimization of loops improves the Code Performance and readability.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.