A study on the cycle usage and optimization of javascript

Source: Internet
Author: User

Usually our writing cycle is roughly like this:

The code is as follows Copy Code
function () {
The way of writing general circulation
for (var i=0; i<values.length; i++) {
...
}
}

Optimization variable Declaration

The above writing in the beginning of learning JS is not wrong, even for the vast majority of object-oriented language is the correct way to write, but JS different with other object-oriented language, he has no block and scope, and some just function scope, so that the above writing is not very normative, In some cases, bugs can also occur, and when you use a variable and then re declare it in a function soon, you may have a logical error. 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. The logical writing is to declare the variable at the beginning of the function, rather than within the loop, to begin defining the variable.

The code is as follows Copy Code
function func () {
To optimize the variable definition of JS, the variable is defined at the starting position to avoid the error of block-level scope
var i;
For (i=0 i<values.length; i++) {
...
}
}

Dynamic collection reading in optimization loops

After optimizing the JS loop variable, we continue to refine it further. The most common way to deal with day-to-day development is DOM, often encounter the situation of cyclic nodelist (do not know what is NodeList object, please go to review the basic knowledge). In general, this divs, which resembles the var divs = document.getElementsByTagName ("div"), is referenced by the NodeList object, and other similar nodelist close relatives have namenodemap and Htmlcollection, these three collections are updated (and dynamically updated) whenever the document structure changes. This can lead to two problems, the first is the performance problem, whenever you modify nodelist read it, you read it is not the previous nodelist but modified dynamically updated nodelist. The second produces an infinite loop of bugs. For example, the following code causes an infinite loop:

  code is as follows copy code
function func ( {
   //loop writing that causes nodelist infinite loops
    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 loop code shown in the example above causes a serious problem, each loop is evaluated to the divs.length, meaning that the query that takes all the DIV elements is run, and then a new DIV element is added to the document, so the value of the div.length increments after each loop. Since I and divs.length each increment at the same time, their values will never be equal, resulting in an infinite loop.

In order to avoid such inefficient and even hidden bugs, the strategy is to minimize the number of accesses to nodelist. Because every time you access nodelist, you run a document based query. So you can consider caching the values obtained from the nodelist. The following is the optimized wording:

  code is as follows copy code
function func ( {
   //Avoid looping writing nodelist infinite loops
    var divs = document.getElementsByTagName (" Div ");
    for (var i=0, len = divs.length; i<len; i++) {
        V Ar Div =document.createelement ("div");
        Document.body.appendChild (DIV);
        alert ("Infinite loop would not happen");
   }
}
Func ()

It's very simple, as long as you cache the divs.length in a variable len inside, then regardless of how the nodelist later, all avoid reading, avoid infinite loops, because the interpretation of JavaScript, So a.b.c.d.e, you need to do at least 4 query operations, first check A and then check a B, and then check C in B, so down. So if this expression repeats itself, as long as possible, you should try to minimize the expression, using the local variable, put it in a temporary place to query. If each query div.length, it is necessary to do an additional operation, and the Len=div.length Var, then less than a query, performance optimization is greatly reflected. At first you will find this writing very uncomfortable, but write a few more times and you will soon get used to the "awkward" way of writing.

Optimization continues to optimize!

Replace i++ with I+=1

This is from the "essence of JavaScript language," the general meaning is that the use of i++ can have potential security problems, + + This operator can be placed in front and can be left behind so that the degree of freedom is too large, if there is no semicolon at the end can cause a few errors such as: A++b++c, It's hard for you to figure out what the previous code means. According to the JavaScript language essence, this + + or-operator encourages overly bizarre writing to cause bad code. In addition to the wrong schemas, they are the second leading culprits for viruses and other security threats. So JSLint has an option plusplus whether to check that these operators are not allowed. Another reason is that i+=1 is more "native" than i++ to improve performance, but the individual believes that readability is reduced, depending on the need to choose. So our code is going to look like this again:

The code is as follows Copy Code
function func () {
Reduced-value iterative optimization cycle
for (var i=values.length-1; i>=0; i--) {
...
}
}

Let the optimization come more violent!

Reduced-value iterative optimization cycle

Most loops use an iterator that starts at 0 and increases to a particular value. In many cases, the iterator, which begins with the maximum value, is more efficient than the constant decrement of the value in the loop. If the processing order of the values does not matter, then the loop can be changed to I minus, optimized as follows:

The code is as follows Copy Code
function func () {
Cyclic optimization Grand
var i; Optimization variable Declaration
var divs = document.getelementsbytagname ("div");
For (i=divs.length-1 i>=0; i-=1) {//optimization loop dynamic set read, decrement iteration, i-=1 instead of i--
...
}
}

Cyclic optimization Grand

If we concentrate all of the above loop optimizations in one piece, the writing will be like this:

The code is as follows Copy Code
12345678 function func () {//cyclic optimization Grand var i;     The optimization variable declares var divs = document.getElementsByTagName ("div"); For (i=divs.length-1 i>=0; i-=1) {//optimized cyclic dynamic collection read, decrement iteration, i-=1 replace I--...}}

To be honest, the above cycle optimizes Grand performance, but also reduces readability to a new height. Your code to write a more coquettish, also have to let people have a point of acceptance that, as a team development, the series above seems to be not particularly desirable, individuals or to promote partial optimization, to optimize performance under the premise of consideration for readability:

The code is as follows Copy Code

function func () {
Reasonable cycle optimization
var I,len; Optimization variable Declaration
var divs = document.getelementsbytagname ("div");
For (i=0, len = divs.length; i<len; i++) {//dynamic collection read in the optimization loop, i+=1 can be substituted if necessary i++
...
}
}

Individuals tend to be more inclined to the above JS cycle. Rational optimization of the cycle to improve the performance of the code, but also the readability, it is stone, all right

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.