JS Performance optimization
Excerpt from: http://www.china125.com/design/js/3631.htm
First, because JS is an interpreted language, the execution speed is much slower than the compiled language. (Note:, Chrome is the first built-in optimization engine, will JS compile the cost code of the browser, other browsers have implemented the JS compilation process. However, even in the new phase of compiling JS, there will still be inefficient code. The following summarizes some of the ways that you can improve the overall performance of your code. 1. Note Scope Remember that the time to access variables outside the current scope increases as the number of scopes in the scope increases. Therefore, accessing global variables is always slower than accessing local variables, because the scope chain needs to be traversed. As long as you can reduce the time spent on the scope chain, you can increase the overall performance of the script. 1). Avoid global lookups (because they involve lookups on scopes) function UpdateUI () { var IMGs = document.getelementbytagname ("img"); for (var i = 0, len = imgs.length; i < Len; i++) { Imgs[i].title = Document.title + " Image "+ i; }" Note that the UpdateUI contains two references to the global variable document object, in particular the document reference in the loop, the number of times is O (n), and each time the scope chain is searched. By creating a local variable that points to the document, you can improve the performance of the function by restricting the global lookup once. function UpdateUI () { var doc = document; var IMGs = doc.getelementbytagname ("img"); for (var i = 0, len = imgs.length; i < Len; i++) { Imgs[i].title = Doc.title + "Imag E "+ i; }}2). Avoid the With statement (with creates its own scope and therefore increases the length of the scope where the code is executed) 2. Choose the right method and itsAs with language, part of the performance problem is related to the algorithm or method used to solve the problem, so it can be optimized by choosing the right method. 1. Avoid unnecessary property lookups accessing variables or arrays in JS is an O (1) operation, which is more efficient than accessing the properties on an object, which is an O (n) operation. Any property lookup on an object takes longer than accessing a variable or array, because a property that has that name must be searched in the prototype chain, that is, the more the property is searched, the longer it takes to execute. Therefore, it should be stored in local variables for the object properties that need to be used multiple times. 2. Optimizing loops Loops is the most common structure in programming, and optimizing loops is an important part of the performance optimization process. The basic optimization steps for a loop are the following: -minus iterations-most loops use an iterator that starts at 0 and increases to a specific value. In many cases, iterators that are constantly decreasing in value from the maximum value are more effective. Simplify termination conditions-because the termination condition is calculated for each cycle, it is necessary to ensure that it is as fast as possible, avoiding property lookups or other O (n) operations. Simplify the loop body-the loop body is the most executed, so make sure it is optimized to the maximum extent possible. Make sure there are no dense calculations that can be easily removed from the loop. After using the test loop-the most common for and while loops are the pre-test loops, such as the Do-while loop, which avoids the calculation of the initial termination condition, because some calculations are faster. for (var i = 0; i < values.length; i++) { process (values[i]);} Optimization 1: Simplified termination condition for (var i = 0, len = values.length; i < Len; i++) { process (values[i]);} Optimization 2: Post-use test cycle (note: After use, test loops need to ensure that there is at least one value to be processed) var I values.length-1;if (i >-1) { do { & nbsp Process (Values[i]); }while (i. >= 0);} 3. Expand loop When the number of loops is determined, eliminating loops and using multiple function calls is often faster when the number of cycles is uncertain, you can use the Duff appliance to optimize. The basic concept of a duff device is to expand a loop into a series of statements by calculating whether the number of iterations is a multiple of 8. as follows://JEFF Greenberg for JS implementation of Duff ' s device//hypothesis: values.length > 0function process (v) { alert (v);} var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];var iterations = Math.ceil (VALUES.LENGTH/8); var startAt = values.length% 8;var i = 0; do { switch (startAt) { Case 0:proces S (values[i++]); case 7:process (values[i++]); Case 6:process (valu es[i++]); case 5:process (values[i++]); Case 4:process (values[i++ ]); case 3:process (values[i++]); case 2:process (values[i++]); &NB Sp Case 1:process (values[i++]); } startAt = 0;} while (--iterations > 0), if you expand the loop above, you can increase the processing speed of the large data set. The next step is to provide a faster duff device technology that divides the do-while cycle into 2 separate loops. (Note: This method is almost 40% faster than the original Duff device.) ) //speed up Your Site (New Riders, 2003) function process (v) {&NBsp Alert (v);} var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];var iterations = Math.floor (VALUES.LENGTH/8); var leftover = values.length% 8;var i = 0; if (Leftover > 0) { do { Process (VA lues[i++]); }while (--leftover > 0);} do { Process (values[i++]); process (values[i++]); process (values[i++]); Process (values[i++]); process (values[i++]); process (values[i++]); Process (values[i++]); process (values[i++]);} while (--iterations > 0), using the unwind loop for big data sets can save a lot of time, but for small datasets, the extra overhead may outweigh the cost. 4. Avoid double interpretation when JS code wants to parse the JS code there will be a double interpretation penalty, this happens when using the eval () function or the function constructor and using settimeout () to pass a string. The following eval ("Alert (' Hello World ');"); Avoid var sayhi = new Function ("Alert (' Hello World ');"); Avoid settimeout ("alert (' Hello World '),", 100);//Avoid the above code is contained in the string, that is, when the JS code is running, a new parser must be shipped to parse the new code. Instantiating a new parser has a negligible overhead, so this code is slower than direct parsing. Here are a few examples, except in the rare case that eval is a must, try to avoid using the above. For function constructors, you can write directly to the general functions. For settimeout, you can pass in a function as the first parameter. as follows: alert (' Hello World '), var sayhi = function () { alert (' Hello World ');}; SetTimeout (function () { alert (' Hello World '); (}, 100); In short, to improve code performance, avoid the code that needs to be interpreted by JS as much as possible. 5. Additional considerations for performance native methods faster-whenever possible, use native methods instead of self-used JS overrides. Native methods are written in a compiled language, such as C + +, and are much faster than JS. The switch statement is faster-if you have a complex set of if-else statements that can be converted to a single switch statement, you can get faster code, and you can further refine the case statement by organizing it in the most probable and most improbable order. Bit operations are faster-the bitwise operation is faster than any boolean or arithmetic operation when doing mathematical operations. Selectively replacing arithmetic operations with bitwise operations can greatly improve the performance of complex computations, such as modulo, logic and logic, or the substitution of bitwise operations. 3. Minimize number of statements the number of statements in the &NBSP;JS code also affects the speed of the actions performed, and a single statement that completes multiple operations is faster than the completion of multiple statement blocks for a single operation. Therefore, we need to find the statements that can be grouped together to reduce the overall execution time. Here are a few patterns 1. Multiple variable declarations //avoid var i = 1;var j = "Hello"; var arr = [1,2,3];var now = new Date (); //advocate var i = 1,&nb Sp j = "Hello", arr = [1,2,3], now = new Date (); 2. Insert iteration value //avoid var name = values[i];i++;& nbsp;//advocates var name = values[i++];3. Use arrays and object literals to avoid using the constructor array (), object () //avoid var a = new Array (); a[0] = 1;a[1]= "Hello"; a[2] = 45; var o = new Obejct (); o.name = "Bill"; o.age = 13; //advocates var a = [1, "Hello", 45];var o = {&NB Sp Name: "Bill", age:13};4. Optimize DOM interaction in JS, the DOM is undoubtedly the slowest part, Dom operations and interactions take a lot of time because they often need to re-render the entire page or part , understanding how to optimize the interaction with the DOM can greatly improve the speed of script completion. 1. Minimizing field updates Once you need access to the DOM section that is part of the page already displayed, then you are on a live update. The site update is called because it requires immediate (on-site) updates to the user's display, with every change, whether it's inserting a single character or removing the entire fragment, there is a performance penalty because the browser needs to recalculate countless dimensions to update. The more live updates are performed, the longer the code takes to complete execution. 2. Multiple use of innerhtml there are two ways to create DOM nodes on a page: Using DOM methods such as createelement () and AppendChild (), and using innerHTML. For small DOM changes, the two are nearly as efficient, but for large dom changes, innerHTML is much faster than the standard DOM method of creating the same DOM structure. When set to a value using innerHTML, the background creates an HTML interpreter and then uses the internal DOM call to create the DOM structure, not the JS-based DOM invocation. Because the internal method is compiled rather than interpreted, execution is faster.
JS Performance Optimization Article one