How to optimize your JS code

Source: Internet
Author: User

The execution efficiency of JS code often directly affects the performance of the page, sometimes, to achieve the same function, different JS code often in the efficiency of a lot of differences, and sometimes just because of our writing habits caused by, of course, in the advanced point of the browser, they have mostly helped us optimize, but in China, The evils of IE6 still exist in large numbers, and we have to consider it. For the JS code optimization, in fact, there are a lot of cases, some of the impact is relatively small, and some are more serious, in this article, I put a few I think the impact of a more serious situation listed for your reference.

1, String stitching

The concatenation of strings is often encountered in our development, so I put it in the first place, we are often accustomed directly to the way to the concatenation of + + string, in fact, the way the stitching is very inefficient, we can use a clever way to achieve the concatenation of strings, that is, the use of array join method.

<div class= "One" id= "one" ></div>
<input type= "button" value= "Low Efficiency" onclick= "func1 ()"/>
<input type= "button" value= "High Efficiency" onclick= "Func2 ()"/>

Efficiency is low
function Func1 () {
var start = new Date (). GetTime ();
var template = "";
for (var i = 0; i < 10000; i++) {
Template + + <input type= ' button ' value= ' a ' > ';
}
var end = new Date (). GetTime ();
document.getElementById ("one"). InnerHTML = template;
Alert ("Spents:" + (End-start) + "millisecond");
}
of high efficiency
function Func2 () {
var start = new Date (). GetTime ();
var array = [];
for (var i = 0; i < 10000; i++) {
Array[i] = "<input type= ' button ' value= ' a ' >";
}
var end = new Date (). GetTime ();
document.getElementById ("one"). InnerHTML = Array.join ("");
Alert ("Spents:" + (End-start) + "millisecond");
}

We will find that the difference is quite obvious under the IE6, in fact, this situation in the high version of IE is also very obvious, but there is no big difference in Firefox, but the second kind of relative efficiency is lower, but only a difference of 2ms or so, and Chrome and Firefox similar. Also here by the way, when we add elements to the array, many people like to use the original method of the array push, in fact, directly with Arr[i] or arr[arr.length] way faster, probably in 10,000 cycles of the situation IE browser will have more than 10 milliseconds difference.

2, for Loop

For loops are situations that we often encounter, let's take a look at the following examples:

<input type= "button" value= "Low Efficiency" onclick= "func1 ()"/>
<input type= "button" value= "High Efficiency" onclick= "Func2 ()"/>
var arr = [];
for (var i = 0; i < 10000; i++) {
Arr[i] = "<div>" + i + "</div>";
}
Document.body.innerHTML + + arr.join ("");

Efficiency is low
function Func1 () {
var divs = document.getelementsbytagname ("div");
var start = new Date (). GetTime ();
for (var i = 0; i < divs.length; i++) {
"Low Efficiency"
}
var end = new Date (). GetTime ();
Alert ("Spents:" + (End-start) + "millisecond");
}
of high efficiency
function Func2 () {
var divs = document.getelementsbytagname ("div");
var start = new Date (). GetTime ();
for (var i = 0, len = divs.length i < len; i++) {
"High Efficiency"
}
var end = new Date (). GetTime ();
Alert ("Spents:" + (End-start) + "millisecond");
}

As can be seen from the table above, Under IE6.0, the difference is obvious, and there is little difference between Firefox and Chrome, this is the case in IE6.0, mainly because for loops in execution, the first case calculates the length each time, and the second is to calculate the length at the beginning and save it to a variable, At a high rate of execution, so when we use a For loop, especially if we need to calculate the length, we should start saving it to a variable. But not as long as the length will appear so obvious differences, if we are just manipulating an array, to get the length of an array, then in fact, the two ways of writing is similar, we look at the following example:

<input type= "button" value= "Low Efficiency" onclick= "func1 ()"/>
<input type= "button" value= "High Efficiency" onclick= "Func2 ()"/>
var arr2 = [];
for (var i = 0; i < 10000; i++) {
Arr2[i] = "<div>" + i + "</div>";
}
Efficiency is low
function Func1 () {
var start = new Date (). GetTime ();
for (var i = 0; i < arr2.length; i++) {
"Low Efficiency"
}
var end = new Date (). GetTime ();
Alert ("Spents:" + (End-start) + "millisecond");
}
of high efficiency
function Func2 () {
var start = new Date (). GetTime ();
for (var i = 0, len = arr2.length i < len; i++) {
"High Efficiency"
}
var end = new Date (). GetTime ();
Alert ("Spents:" + (End-start) + "millisecond");
}

As you can see from the table above, if it's just an array, we're looking at two different ways of writing, but if we raise the loop up to 100,000 times, it's just a few milliseconds, so in the case of an array, I think it's all the same. For the optimization of the For loop, there are also many points, some people think that the use of-=1, or from a large to small loop, etc., I think is completely unnecessary, these optimizations are often not shown at all, in other words, just the computer level of small changes, But what we bring is the readability of the code is greatly reduced, so it is not worth the candle.

3, reduce the page redraw

Reduce page Redraw Although the essence is not the optimization of JS itself, but it is often caused by JS, and redrawing the situation is often seriously affect the performance of the page, so it is necessary to take out, we look at the following example:

<div id= "Demo" ></div>
<input type= "button" value= "Low Efficiency" onclick= "func1 ()"/>
<input type= "button" value= "High Efficiency" onclick= "Func2 ()"/>
var str = "<div> This is a test string </div><div> this is a test string </div><div> this is a test string </div>< Div> This is a test string </div><div> this is a test string </div><div> this is a test string </div><div> This is a test string </div><div> this is a test string </div><div> this is a test string </div><div> this is a test string </ Div><div> This is a test string </div><div> this is a test string </div><div> this is a test string </div> ";
Efficiency is low
function Func1 () {
var obj = document.getElementById ("demo");
var start = new Date (). GetTime ();
for (var i = 0; i < i++) {
obj.innerhtml + = str + i;
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}
of high efficiency
function Func2 () {
var obj = document.getElementById ("demo");
var start = new Date (). GetTime ();
var arr = [];
for (var i = 0; i < i++) {
Arr[i] = str + i;
}
obj.innerhtml = Arr.join ("");
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}

In the example, I only used 100 cycles, because if you use 10,000 cycles, the browser is basically stuck, but even 100 cycles, let's look at the results below.

What can be seen is that this is a stunning result, just 100 cycles, no matter what browsers, there are so big differences, and we also found that here, IE6 efficiency than Firefox is much better, Visible Firefox in the page redraw this aspect does not do some optimization. Also note here is that the general impact of the page redraw is not only innerhtml, if you change the style of elements, position and so on will trigger the page redraw, so in peacetime must pay attention to this point.

4. Reduce the number of lookups on the scope chain

We know that JS code in the execution of the time, if you need to access a variable or a function, it needs to traverse the scope of the current execution environment chain, and traversal from the scope of the chain from the front-end level backward traversal, until the global execution environment, so here is often a situation, That is, if we need to frequently access variable objects of the global environment, we must iterate at the first level of the current scope chain each time, which is obviously time-consuming, and let's look at the following example:

<div id= "Demo" ></div>
<input id= "BUT1" type= "button" onclick= "Func1 ()" value= "inefficient"/>
<input id= "But2" type= "button" onclick= "Func2 ()" value= "High Efficiency"/>

function Func1 () {
var start = new Date (). GetTime ();
for (var i = 0; i < 10000; i++) {
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
var but1 = document.getElementById ("but1");
var but2 = document.getElementById ("But2");
var inputs = document.getElementsByTagName ("input");
var divs = document.getelementsbytagname ("div");
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}
function Func2 () {
var start = new Date (). GetTime ();
var doc = document;
for (var i = 0; i < 10000; i++) {
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
var but1 = Doc.getelementbyid ("but1");
var but2 = Doc.getelementbyid ("But2");
var inputs = Doc.getelementsbytagname ("input");
var divs = doc.getelementsbytagname ("div");
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}

In the code above, the second scenario is to first save the variables of the global object into the function, and then direct access to the variable, and the first scenario is to traverse the scope chain every time, until the global environment, we see that the second situation actually traverses only once, and the first one is traversed every time, So let's look at the results of its implementation:

As can be seen from the table above, the difference is still very obvious in the IE6, and the difference is very obvious in the case of multilevel scope chain and multiple global variables.

5. Avoid double interpretation

The double interpretation is also something we often encounter, and sometimes we don't take into account that this situation affects efficiency, and the double explanations are usually encountered when we use Eval, new function, and settimeout, and we look at the following example:

<div id= "Demo" ></div>
<input id= "BUT1" type= "button" onclick= "Func1 ()" value= "inefficient"/>
<input id= "But2" type= "button" onclick= "Func2 ()" value= "High Efficiency"/>
var sum, num1 = 1, num2 = 2;
function Func1 () {
var start = new Date (). GetTime ();
for (var i = 0; i < 10000; i++) {
var func = new Function ("sum+=num1;num1+=num2;num2++;");
Func ();
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}

function Func2 () {
var start = new Date (). GetTime ();
for (var i = 0; i < 10000; i++) {
SUM+=NUM1;
num1+=num2;
num2++;
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}

In the first case we use the new function for a double interpretation, and the second is to avoid the double interpretation, we look at the performance in different browsers:

As you can see, in all browsers, double interpretation has a lot of overhead, so try to avoid double explanations in practice.

Thanks to "Seasunk" for the 4th Test report wrong correction, has now been modified. As for the last point, the func1 was initialized every time, and there was no comparability, so I changed eval, and found that Under the IE6.0 still has the influence, moreover under the Firefox, uses the eval to the efficiency influence degree to be more formidable, under the Firefox, if 10,000 times cycle, needs more than 10 seconds time, therefore I has changed the cycle to 1000 times. Look at the code and the report.

var sum, num1 = 1, num2 = 2;
function Func1 () {
var start = new Date (). GetTime ();
for (var i = 0; i < 1000; i++) {
Eval ("sum+=num1;num1+=num2;num2++;");
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}
function Func2 () {
var start = new Date (). GetTime ();
for (var i = 0; i < 1000; i++) {
SUM+=NUM1;
num1+=num2;
num2++;
}
var end = new Date (). GetTime ();
Alert ("spents" + (End-start) + "milliseconds");
}


Add:

 increase the speed of string accumulation when using AJAX to submit information, I may often need to assemble some larger strings to complete post submissions through XMLHTTP. While the practice of submitting such a large message does not look elegant, sometimes we may have to face this demand. So what is the cumulative speed of strings in JavaScript? Let's do the following experiment first.
Add a string that is 30000 long.
/* Test Code 1-Time-consuming: 14.325 sec/var str = ""; for (var i = 0; i < 50000 i++) {str = "xxxxxx";} This code takes 14.325 seconds, and the result is not ideal.
Now we'll change the code to the following form:/* Test Code 2-time: 0.359 seconds/var str = "";
    for (var i = 0; i < i++) {var sub = "";
    for (var j = 0; J < + j) {sub = = "XXXXXX";
str + = sub; This code takes 0.359 seconds. As a result, we're just assembling some smaller strings and then assembling them into larger strings. This approach can effectively reduce the amount of memory replicated data later in the string assembly. Knowing this principle, we can further disassemble the above code and test it later.
The following code takes only 0.140 seconds.    
/* Test Code 3-Time-consuming: 0.140 sec/var str = "";
    for (var i1 = 0; i1 < 5; i1++) {var str1 = "";
        for (var i2 = 0; i2 < i2++) {var str2 = ""; for (var i3 = 0; i3. 
)

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.