Among the suggestions (I) of JavaScript on improving website performance, several suggestions are put forward for improving website performance from HTTP requests to page rendering. This article is a summary from the perspective of JavaScript performance after learning another book by Steve Sounders, "Advanced Guide to High-Performance Website Construction".
JavaScript performance is the key to implementing high-performance web applications
--Steve Sounders
1. Utilize js scope chain
scope chain
When executing a piece of JavaScript code (global code or function), the JavaScript engine will create a scope for it, also known as the Execution Context. After the page is loaded, a global scope will be created first, and then each function will be executed, a corresponding scope will be established, thus forming a scope chain. Each scope has a corresponding scope chain, the head of the chain is the global scope, and the tail of the chain is the current function scope.
The purpose of the scope chain is to parse identifiers. When the function is created (not executed), this, arguments, named parameters and all local variables in the function will be added to the current scope. When JavaScript needs to find the variable X (this process is called variable resolution), it will first search for whether there is an X attribute from the end of the chain in the scope chain, that is, the current scope. If it is not found, continue to search along the scope chain until the chain head, that is, the global scope chain, and the variable is not found, it is believed that there is no x variable on the scope chain of this code, and a reference error (ReferenceError) exception is thrown.
Managing the depth of the scope chain is a simple way to improve performance with just a small amount of work. We should avoid slow execution speeds due to unintentional growth of the scope chain.
Use local variables (short scope chains as much as possible)
If we understand the concept of scope chain, then we should be clear that the JavaScript engine parsing variables is related to the depth of scope chain. Obviously, local variables are at the end of the chain and have the fastest access speed. Therefore, a good experience is: when any non-local variable is used more than once, please use local variables to store them, for example:
function changeDiv(){document.getELementById('myDiv').className = 'changed';document.getELementById('myDiv').style.height = 150;}Here, myDiv dom element is referenced twice. For faster reference, we should store it with a local variable. The benefits of doing this not only shortens the scope chain, but also avoid duplicate queries of DOM elements:
function changeDiv(){var myDivStyle = document.getElementById('myDiv').style;myDiv.className = 300;myDiv.style.height = 150;}Avoid using with (do not grow scope chains)
Generally, during code execution, the scope chain of the function is fixed, but with can temporarily increase the scope chain of the function. with is used to display object properties as local variables to make them easy to access, for example:
var user = {name:'vicfeel',age:'23'};function showUser(){var local = 0;with(user){console.log("name" + name);console.log("Age" + age);console.log(local);}}showUser();In this example, with a temporary scope is added to the end of the showUser scope chain, which stores all the properties of the user object, that is, the scope chain with the code is increased. In this code, local variables like local change from the first object at the end of the chain to the second, which naturally slows down the access of identifiers. Until the with statement is over, the scope chain resumes growth. Because of this flaw of with, we should try to avoid using the with keyword.
2 More reasonable flow control
Like other programming languages, JavaScript has some flow control statements (loops, conditions, etc.), and using appropriate statements on each link can greatly improve the running speed of the script.
Quick condition judgment
When it comes to conditional judgment, the first way to avoid:
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 for conditional judgment is that the level is too deep. When I want value = 7, the time consumes much longer than value = 0, which greatly loses performance and is poor readability.
A better way to make judgments with switch.
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 not only improves readability, but also requires faster query time than if. But if if is faster than switch if only one or two conditions
In JavaScript, there is another way to query conditionals. The previous example was to return different values according to the value, which just happens to be able to use arrays to implement mapping query of hash tables.
//Define the array var results = [result0,result1,result2,result3,result4,result5,result6,result7];//Query result return results[value];
This method of array is more effective when the query range is large, because it does not have to detect upper and lower boundaries, and only needs to fill in the index value to query. Its limitation is that the condition corresponds to a single value rather than a series of operations. Therefore, we must comprehensively combine the actual situation, choose the appropriate judgment method of conditions, and maximize performance.
Quick cycle
There are 4 loop methods in JavaScript for loop, do-while loop, while loop and for-in loop. Here is a very commonly used recycling method:
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. Each loop i must be compared with the length of values. Querying attributes is more time-consuming than local variables. If the number of loops is larger, the more time-consuming it will be. Therefore, it can be optimized like this:
var values = [1,2,3,4,5];var length = values.length;//Local variable storage array length for(var i = 0;i < length;i++){process(values[i]);}This code can also continue to optimize, decreasing the loop variable to 0 instead of adding to the total length.
var values = [1,2,3,4,5];var length = values.length;for(var i = length;i--;){ //Decrement to 0process(values[i]);}Here, the end of the loop is transformed to compare with 0, so the speed of each loop is faster. Depending on the complexity of the loop, this simple change can save about 50% of the time than before.