This article describes common techniques for JavaScript to improve performance. Share it for your reference, as follows:
1. Pay attention to scope
As the number of scopes in the scope chain increases, the time to access variables outside the current scope also increases. Accessing global variables is always slower than accessing local variables because you need to traverse the scope chain.
1). It is always correct to avoid global searches to store global objects that will be used multiple times in a function as local variables.
2). Avoid that with statement with creates its own scope, thus increasing the length of the scope chain in which the code is executed.
2. Choose the right method
Part of the performance problem is related to the algorithm or method used to solve the problem.
1). Avoid unnecessary attribute searches
In computer science, the complexity of an algorithm is represented by the O symbol. The simplest and fastest algorithm is the constant value, namely O(1). After that, the algorithm becomes more and more complex and takes longer to execute. Common JavaScript algorithm types are:
Constant: No matter how many values there are, the execution time is constant. Generally, it represents a simple value and the value stored in a variable.
Logarithm: The total execution time is related to the number of values, but it is not necessary to obtain each value to complete the algorithm. For example: binary search
Linear: The total execution time is directly related to the number of values. For example: iterate through all elements in an array
Square: The total execution time is related to the number of values, and each value must be obtained at least n times. For example: Insert sort
Cube: The total execution time is related to the number of values, and each value must obtain at least squares of n.
Using variables and arrays is more efficient than accessing properties on objects. The search for any attribute on an object takes longer than accessing a variable or array, because a property with that name must be searched in the prototype chain.
Generally speaking, as long as the complexity of the algorithm can be reduced, it must be minimized as much as possible. Use as many local variables as possible to replace property lookups with value lookups. Furthermore, if you can access it with digitized array positions, or use named attributes (such as NodeList objects), then use the array position.
2). Optimize loop
a. Impairment Iteration In many cases, iterators that start from the maximum value and continuously impair in the loop are more efficient.
b. Simplified Termination Conditions Since each cycle process calculates the terminating condition, it must be ensured as fast as possible.
c. Simplified loop body The loop body is the most performed, so make sure it is optimized to the maximum extent. Make sure there are no intensive calculations that can be easily removed from the loop.
d. The most commonly used for and while loops in the post-test loops are pre-test loops. Post-test loops such as do-while can avoid the initial termination of the calculation of the condition and therefore faster.
3). Expand the loop when the number of loops is determined, eliminating the loop and using multiple function calls are often faster. For example, the famous Duff device
4). Avoid double explanation
When JavaScript code wants to parse JavaScript, there will be a double-interpretation penalty. The following example:
eval("alert('Hello world!')");//Some codes evaluate valuesFixed:
alert('Hello world'); var saysHi = new Function("alert('Hello world!')");Fixed:
var saysHi = function(){ alert("Hellow world!');}; setTimeout("alert('Hellow world!')",500);Fixed:
setTimeout(function)({ alert('Hellow world!');},500);5). Other methods
Native methods are faster - whenever possible, use native methods instead of rewriting one in JavaScript yourself. Native methods are written in compiled languages such as C/C++, so they are much faster than JavaScript. The most easily forgotten thing in JavaScript is the complex mathematical operations that can be found in Math objects; these methods are much faster than any other method written in JavaScript, such as sine and cosine.
Switch statements are faster - if there is a complex if-else statement that can be converted into a single switch statement, you can get faster code. You can also organize the case statements in the most likely order to the least likely order to further optimize the switch statements.
Bit operators are faster - when mathematical operations are performed, bit operations are faster than any Boolean or arithmetic operations. Selective conversion of bit operations can greatly improve the performance of complex calculations. For example, modulo, logic and sum logic, you can consider using bit operations to replace them.
3. Minimize the number of statements
1). Multiple variable declarations
like:
//4 statements---It's a waste of var count = 5;var color = "blue";var values = [1,2,3];var now = new Date();
optimization:
var count = 5,color = "blue", values = [1,2,3],noiw = new Date();
This optimization is very easy to do in most cases and is much faster than a single variable declaration separately.
2). Insert iterative value
like:
var name = values[i];i++;
optimization:
var name = values[i++];
3). Use arrays and object literals
like:
var values = new Array(); ---> var values = [];
var obj = new Object(); ---> var obj = {};
4. Optimize DOM interaction
1). Minimize on-site updates
Once you need to access the DOM part is part of the page that has been displayed, you are doing a live update. The reason why it is called a live update is that the page needs to be updated immediately (on-site) to the user's display. Whether it is inserting a single character or removing the entire clip, there is a performance penalty because the browser has to recalculate countless sizes to update.
example:
var list = document.getElementById("myList"); for(var i = 0;i < 10;i++){ var item = document.createElement("li"); list.appendChild(item); item.appendChild(document.createTextNode("Item "+i));}This adds 10 projects, and this operation requires a total of 20 on-site updates. The following is to improve the following method of creating document fragments:
var list = document.getElementById("myList");var fragment = document.createDocumentFragment();for(var i = 0; i < 10;i++){ fragment.appendChild(item); item.appendChild(document.createTextNode("Item "+i));}list.appendChlid(fragment);In this example, there is only one live update, which happens after all projects are created. The document fragment is used as a temporary placeholder to place the newly created project. Then use appendChild() to add all items to the list. Remember that when appendChild() is passed in the document fragment, only the child nodes in the fragment are added to the target, and the fragment itself will not be added.
Once you need to update the DOM, consider using document fragmentation to build the DOM structure and then add it to the existing document.
2). Use innerHTML
There are two ways to create DOM nodes on a page: using DOM methods such as createElement(), appendChild(), and using innerHTML for small DOM changes, both methods are similar in efficiency. For large DOM changes, using innerHTML is much faster than using standard DOM methods to create the same DOM structure. Similarly, using innerHTML at one time is much faster than using innerHTML multiple times.
3). Use event proxy (simple, omitted)
4). Pay attention to NodeList
Minimizing the number of accesses to NodeList can greatly improve script performance.
The NodeList object is returned when the following occurs:
a. Call to getElementsByTagName() is made
b. Get the childNodes property of the element
c. Get the attributes attributes of the element
d. Accessed special collections, such as document.forms, document.images, etc.
It is necessary to understand that when using NodeList objects, reasonable use will greatly improve the execution speed of code.
The function throttling introduced earlier is also a very important aspect. Especially when multiple loops are very performance-consuming, this method is very useful.
PS: For JavaScript compression, reducing the code size is also an effective way to improve JavaScript performance. Here are two very practical compression tools:
JavaScript compression/formatting/encryption tools:
http://tools.VeVB.COM/code/jscompress
jsmin online js compression tool:
http://tools.VeVB.COM/code/jsmincompress
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.