JavaScript improve site performance optimization suggestions (ii) _JAVASCRIPT skills

Source: Internet
Author: User
Tags array length http request

In JavaScript on improving the performance of the site several suggestions (i), from the HTTP request to the page rendering several aspects to improve the performance of the site has put forward several suggestions, this article is a study of Steve Sounders's another book, "High-performance Web site Building Advanced Guide," after From the point of view of JavaScript performance summary, we share.

JavaScript performance is key to implementing high-performance Web applications

--steve Sounders

1 Using JS scope chain

Scope chain (scope chain)

When you execute a piece of JavaScript code (global code or function), the JavaScript engine creates a scope for it, also known as the execution context (Execution), which creates a global scope after the page is loaded, and then executes a function every time. Creates a corresponding scope, which creates a chain of scopes. Each scope has a corresponding scope chain, and the chain header is a global scope, and the chain end is the current function scope.

The role of a scope chain is used to resolve identifiers, and when a function is created (not executed), the This, arguments, named arguments, and all local variables in the function are added to the current scope when JavaScript needs to find the variable x (this process is called a variable resolution). It first looks for the X attribute from the chain end of the scope chain, which is the current scope. If you do not find it, follow the scope chain until you find the chain, which is the global scope chain, and you do not find the variable, and you don't see the x variable on the scope chain of the code. and throws a reference error (REFERENCEERROR) exception.

Managing the depth of the scope chain is a simple way to get high performance with a small amount of work, and we should avoid slow execution by inadvertently increasing the scope chain.

Use local variables (try to shorten the scope chain)

If you understand the concept of the scope chain, then we should be aware that the JavaScript engine's parsing time is related to the depth of the scope chain, and it is obvious that local variables are the fastest at the end of the chain, so a good experience is that when any non-local variable is used more than once, Use local variables to store them, for example:

function Changediv () {
document.getElementById (' mydiv '). ClassName = ' changed ';
document.getElementById (' Mydiv '). Style.height = N.

Here Mydiv this DOM element is referenced two times, for faster reference, we should store it with a local variable, the benefit not only shortens the scope chain, but also avoids the repeated query of DOM elements:

function Changediv () {
var mydivstyle = document.getElementById (' mydiv '). style;
Mydiv.classname =;
MyDiv.style.height =;

Avoid using with (do not grow the scope chain)

Generally, the scope chain of functions is fixed during code execution, whereas with can temporarily increase the scope chain of functions. With is used to display object properties as local variables to make them accessible, for example:

var user = {
name: ' Vicfeel ', age
: '% '
};
function Showuser () {
var local = 0;
With (user) {
console.log ("name" + name);
Console.log ("ages" + age);
Console.log (local);
}
Showuser ();

In this example, a temporary scope is added to the chain end of the showuser scope chain, which stores all the properties of the user object, that is, the scope chain of the with code, which, in this code, Local variables like the one from the end of the chain become the second, naturally slowing down the access of identifiers. The scope chain resumes growth until the with statement ends. Because of this flaw with, we should try to avoid using the WITH keyword.

2 more reasonable flow control

JavaScript, like other programming languages, has some flow control statements (loops, conditions, etc.), and the use of appropriate statements on each link can greatly improve the speed of the script.

Quick condition Judgment

One of the first ways to avoid a conditional judgment is to use it:

if (value = = 0) {return
result0;
}
else if (value = = 1) {return
result1;
}
else if (value = = 2) {return
result2;
}
else if (value = = 3) {return
result3;
}
else if (value = = 4) {return
result4;
}
else if (value = = 5) {return
result5;
}
else if (value = = 6) {return
result6;
}
else{return
result7;
}

The main problem with this method of using if conditional judgment is that the hierarchy is too deep, and when I want value = 7 o'clock, the time spent is much longer than value = 0, which greatly loses performance and is of poor readability.

A better way to use a switch to judge.

SWITHC (value) {case
0: return
result0;
Case 1: Return
result1;
Case 2: Return
result2;
Case 3: Return
RESULT3;
Case 4: Return
RESULT4;
Case 5: Return
RESULT5;
Case 6: Return
result6;
Default: Return
result7;
}

This will not only improve readability, but also query time faster than if. But if there are only one or two conditions, if it is faster than the switch

In JavaScript, there is another way in which a conditional query can be used to map a hash table just by using an array to return different values based on the value.

Define array
var results = [RESULT0,RESULT1,RESULT2,RESULT3,RESULT4,RESULT5,RESULT6,RESULT7];
Query results return
Results[value];

This array approach is more efficient when the scope of the query is large, because it does not have to detect the upper and lower bounds, just fill in the index value can be queried. Its limitation is that the condition corresponds to a single value rather than a series of operations. Therefore, to synthesize the actual situation, choose the right conditions to judge the way to maximize performance.

Quick Loop

There are 4 kinds of loops in javascript for loops, do-while loops, while loops, and for-in loops. Here is a very common way to recycle:

var values = [1,2,3,4,5];
for (var i = 0;i < values.length;i++) {
process (values[i]);
}

We can see that the most obvious optimization of this code is values.length, where each loop i is compared to the length of values, and query attributes are more time-consuming than local variables, and if the number of loops is greater, this time is more obvious, so you can optimize:

var values = [1,2,3,4,5];
var length = values.length;//local variable store array length for
(var i = 0;i < length;i++) {
process (values[i));
}

This code can also be optimized to decrement the loop variable to 0, rather than accumulator to the total length.

var values = [1,2,3,4,5];
var length = values.length;
for (var i = length;i--;) {//descending to 0
process (values[i]);

This will transform the loop over to 0, so each cycle is faster and, depending on the complexity of the cycle, this simple change can save about 50% of the time.

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.