Continuing with our JavaScript optimization plan, we have made every effort to reduce the size of Javascript script files for transmission in the last period. However, this is not enough because Javascript Code The speed is divided into two parts: download time (depending on the file size) and execution speed (depending on the code Algorithm ). After the client loads the Javascript script, the real speed of the trip depends on whether the Code itself is optimized. This article describes how to optimize the code execution speed (it sounds very technical ). In the browser that follows the scope, the default JavaScript variable range is window, that is, global variables. Variables in the window are released only after the page is closed from the browser. While JavaScript also has the concept of local variables (private variables), which are usually released after being executed in a container (such as a function. Therefore, it is easy to understand that when a variable is called, the interpreter will find the variable from the lower (container) to the upper (window), and the variable itself will take a little time. Therefore, the interpreter is in the function tree (JavaScript advanced Program In design, the shorter the traversal range is, the faster the script runs. I am not good at teaching. Please understand the following code: var Country = "China"; function fn1 () {alert (country);} function FN2 () {var province = "Zhejiang"; fn1 () ;}function fn3 () {var city = "Hangzhou"; FN2 () ;}fn3 (); for more information, click here and here. After using local variables to understand the above details, we can understand it very well. Using local variables can lead to faster execution, because the interpreter does not need to leave the current execution range because of searching for variables. At the same time, the local variables will be released after being allowed, so they will not continue to occupy the memory. It should be noted that using closures will break this rule. For more information, see here and my previous questions. Avoid using the with statement to search for a variable with a smaller range and faster speed, so it is easy to understand the reasons for avoiding using the with statement. For example, alert (document. title); alert (document. body. tagname); alert (document. location); can be written as with (document) {alert (title); alert (body. tagname); alert (location);} Although the code is reduced, it is easy to understand. However, when using the with statement, force the interpreter to not only search for local variables in the function tree (range tree), but also to forcibly detect each variable and the specified object, check whether the variable or attribute exists. Therefore, it is best to avoid using the with statement. The shortest code is not always the most efficient. Choosing the right algorithm seems nonsense. All programmers understand how important the right algorithm is to the efficiency of their journey. There is not much explanation here. You can refer to this article and this article. I always believe that good experiences are obtained in actual coding. Like most programming languages, the loop method uses JavaScript to consume a large amount of execution time. Therefore, keeping the loop efficient can reduce the execution time. The following are some tricks that we have obtained from the book. There is an interesting example of a reverse loop. For example, a typical loop writes for (VAR I = 0; I <element. length; I ++ ){//...} but writing the following statement will help reduce the complexity of the algorithm, because it uses constant (o) as a conditional loop to reduce the execution time for (VAR I = element. length-1; I> = 0; I --){//...} the explanation in the book may be incomprehensible, so I will write it again as VAR element_length = element. length; For (VAR I = 0; I <element_length; I ++ ){//...} it may be better understood because it does not repeatedly obtain the Length attribute of the element in the loop, but the change method in the book lacks a variable. Using do... while to replace the while statement can further reduce the execution time. For example, VAR I = 0; while (I <element. length ){//... I ++;} can be rewritten to do... the while statement is like this var I = 0; do {//... I ++;} while (I <element. length); of course, according to the previous trick, We can optimize it to this way var I = element. length-1; do {//...} while (-- I> = 0); this is because do... the while statement first loads the loop body and then performs conditional judgment. However, I think the logic of the program is preferred. When conditions are used to judge and optimize if statements using If and multiple else statements, the possible conditions will be placed first, and so on. At the same time, try to reduce the number of else and if, and arrange the conditions according to the binary tree. For example, if (I> 0 & I <10) {alert ('between 0 and 10');} else if (I> 9 & I <20) {alert ('between 10 and 20');} else if (I> 19 & I <30) {alert ('between 19 and 30 ');} else {alert ('out of range');} You can write this code as if (I> 0) {if (I <10) {alert ('between 0 and 10');} else {if (I <20) {alert ('between 10 and 20');} else {if (I <30) {alert ('between 20 and 30');} else {alert ('greater than or equal 30') ;}}} else {alert ('less than or equal 0. Although it looks very complicated, it has considered the potential condition judgment of a lot of code, so it runs faster. Switch and if are already common problems. Generally, when two if... else statements are used, the switch statement is recommended. This can make the code clearer and more efficient. The case condition can also use any type of value. Statement slimming can be easily understood. The fewer statements in the script, the shorter the execution time required (it sounds like there is a conflict with the above view ). There are many ways to shorten the statements in the Code, such as the following tricks. It is obvious to define multiple variables. One statement can define multiple variables. This not only reduces the code size, but also reduces the number of statements to reduce execution time. For example, the following code var website = "www.gracecode.com"; var havelunch = function (){...}; you can simplify it to VaR website = "www.gracecode.com", havelunch = function (){...}; I believe that such a statement will not bring much obstacle to reading. The iteration factor uses the iteration factor to merge statements as much as possible. For example, VAR girlfriend = Girl [I]; I ++; can be replaced by VAR girlfriend = Girl [I ++. However, we recommend that you be especially careful with the differences between I ++ and I (effects of the damn C language ). The array and object literal are mentioned in the previous article. We will not repeat them here. For example, VAR mysite = new object; mysite. author = "feelinglucky"; mysite. location = "http://www.gracecode.com"; you can streamline it to VaR mysite = {Author: "feeinglucky", Location: "http://www.gracecode.com. Other tricks give priority to built-in methods such as function power (number, n) {var result = number; For (VAR I = 1; I <n; I ++) the {result * = number;} return result;} function can use math. pow. Javascript already has many ready-made built-in methods, so it is best to use them as long as they are allowed. Store common values when the same value is used multiple times, you can store it in a local variable for quick access. I'm sorry for this. Dom operations save the processing of DOM by Dom operations JavaScript, which may be one of the most time-consuming operations. Every JavaScript operation on Dom, the browser will change the page performance and re-render the page, resulting in significant time loss. A more environmentally friendly approach is to try not to perform Dom operations in the Dom. See the following example to add 10 entries for UL var oul = document. getelementbyid ("ulitem"); For (VAR I = 0; I <10; I ++) {var Oli = document. createelement ("Li"); oul. appendchild (Oli); Oli. appendchild (document. createtextnode ("item" + I);} at first glance, it seems impeccable, but this Code does have a problem. The first is oul in the loop. appendchild (Oli); after each execution, the browser will re-render the page. Second, add a text node (Oli. appendchind (document. createtextnode ("item" + I);), this will also cause page re-rendering. Each operation will cause two page re-rendering times, totaling 20 times. To solve this problem, as mentioned above, reduce the DOM operation and add the list project after the text node is added. The following code can complete the same task as the preceding code. VaR oul = document. getelementbyid ("ulitem"); var otemp = document. createdocumentfragment (); For (VAR I = 0; I <10; I ++) {var Oli = document. createelement ("Li"); Oli. appendchild (document. createtextnode ("item" + I); otemp. appendchild (Oli);} oul. appendchild (otemp. Relatively messy (x) HTML documents that are friendly to web standards Article For the page, the Javascript execution speed is also different. The browser has different page processing modes, which may be one of the reasons for compiling pages that comply with web standards. For more information, see here and some comments. Although cache ajaxajax provides asynchronous page request calls, do not forget that it still accesses the server. Javascript can be used as the driver layer as a cache. Although it will be released after the page is loaded again, it is a good message for the server. I wrote so many things without knowing it. Many things are published in books. Javascript advanced programming is indeed a rare good book. I suggest you have a chance to read it. This book is not expensive, 59 RMB (may be at a discount elsewhere), it is a double-precision happiness for smokers, but it is much more pleasant than cigarettes.
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