How to improve JavaScript execution efficiency and performance in front-end development in a very important place, this section to study how to do in peacetime project process, improve JavaScript performance and operational efficiency, the need for friends can refer to the next
How to improve JavaScript execution efficiency and performance in front-end development in a very important place, this section to study how to do in peacetime project process, improve JavaScript performance and operational efficiency.
Cycle
Loop is a very common control structure, most of the things to rely on it to complete, in JavaScript, we can use for (;;), while (), for (in) three kinds of loops, in fact, these three kinds of loops in the efficiency of the very poor, because he needs to query the hash key, Use as little as you can. for (;;) And while loop performance should be said basic (usually used) equivalent.
In fact, how to use these two loops, there is a great emphasis. The final conclusion is:
If the loop variable is incremented or decremented, do not assign a value to the loop variable alone, it should use the nested + + or--operator when it is last read. If you want to compare the length of the array, you should put the long property of the array in a local variable and reduce the number of queries. For example, suppose Arr is an array, the best way to traverse elements is:
Copy the code code as follows:
for (var i = 0, len = arr.length; i)
Or, if it doesn't matter the order:
Copy the code code as follows:
for (var i = arr.length; i > 0; i--) {
...
}
Local variables and global variables
Local variables are faster to access than global variables, because global variables are actually members of global objects, and local variables are placed in the stack of functions.
Do not use eval
Using Eval is equivalent to invoking the interpretation engine again at run time to run the content, which can take a lot of hours. The function template can be implemented by using the closures supported by JavaScript (refer to the relevant contents of the functional programming for the contents of the closures).
Reduce object Lookups
Because of the explanatory nature of JavaScript, A.B.C.D.E requires at least 4 queries, checking A and then checking the B in a, and checking the C in B, so down. So if the expression repeats itself, as long as it is possible, the expression should be as few as possible, you can use the local variable, put it in a temporary place to query. This can be combined with the loop, because we often have to loop according to the length of the string, array, and usually this length is constant, such as every query a.length, an additional operation, and the pre-len=a.length Var, then one less query.
String connection
If you are appending strings, it is best to use the S+=ANOTHERSTR operation instead of using S=S+ANOTHERSTR. If you want to connect more than one string, you should use less than + =, such as s+=a;s+=b;s+=c; it should be written as S+=a + B + C; If you are collecting strings, such as multiple + = operations on the same string, it is best to use a cache. How to use it? Use a JavaScript array to collect and finally connect using the Join method.
As follows
<script>
var buf = new Array ();
for (var i = 0; i <; i++) {
Buf.push (i.ToString ());
}
var all = Buf.join ("" ");
</script>
Type conversions
Type conversion is a common mistake, because JavaScript is a dynamic type language, and you cannot specify the type of the variable.
1. Convert the number to a string, apply "" "" "+ 1, although it looks uglier, but in fact this efficiency is the highest, performance said:
Copy the code code as follows:
("" "+) > string () >. toString () > New String ()
This is a bit similar to the following "direct volume", as far as possible, the internal operations that can be used at compile time are faster than the user actions that are used at run time.
String () is an intrinsic function, so it is fast, and. ToString () queries the function in the prototype, so the speed is inferior, and new String () is used to return an exact copy.
2. Floating-point conversion to Integer, this is more error-prone, many people like to use parseint (), in fact, parseint () is used to convert a string into a number, rather than floating-point numbers and integers between the conversion, we should use Math.floor () or Math.Round ().
In addition, unlike the problem in the second section of object lookup, math is an internal object, so Math.floor () does not actually have much of a query method and call time, and the speed is the fastest.
3. For custom objects, if the ToString () method is defined for type conversion, it is recommended to explicitly call ToString (), since the internal operation attempts to convert the ToString () method of the object to a string after attempting all possibilities. So it is more efficient to call this method directly.
Use Direct volume
In fact, this effect is relatively small, can be ignored. What is the use of direct volume, for example, JavaScript support using [Param,param,param,...] To express an array directly, we used to use the new array (Param,param,...), which is directly explained by the engine, which calls an array internal constructor, so it's a little bit faster.
Similarly, var foo = {} is also more in the same way than var foo = new Object (); Fast, var reg =/: /; is faster than Var reg=new RegExp ().
String Traversal operations
Loop the string, such as replace, find, should use regular expression, because its own JavaScript loop speed is relatively slow, and the operation of the regular expression is written in C language API, the performance is very good.
Advanced objects
Custom high-level objects and date, RegExp objects consume a lot of time when they are constructed. If you can reuse it, you should adopt a caching approach.
DOM-related
Inserting HTML
Many people like to use document.write in JavaScript to generate content for a page. In fact, this is less efficient, if you need to insert HTML directly, you can find a container element, such as specifying a div or span, and set their innerhtml to insert their own HTML code into the page.
Object Query
Using the [""] query is faster than. Items (), which is the same as the idea of reducing object lookups earlier, calling. Items () Adds a call to the query and function.
Creating a DOM node
Usually we may use strings to write HTML directly to create nodes, in fact, this
Cannot guarantee the validity of the code
Low efficiency in string manipulation
So it should be with the Document.createelement () method, and if there is a ready-made template node in the document, it should be the CloneNode () method, because after using the createelement () method, you need to set the attributes of multiple elements. Using CloneNode () reduces the number of times a property is set-and if you need to create many elements, you should first prepare a template node.
Timer
If you are targeting code that is constantly running, you should not use settimeout, but should be using setinterval. SetTimeout each time you reset a timer.
Other
Scripting engine
I tested Microsoft's JScript more efficiently than Mozilla's spidermonkey, whether it's execution speed or memory management, because JScript is not updated at all. But SpiderMonkey cannot use ActiveXObject.
File optimization
File optimization is also a very effective means to delete all the spaces and comments, put the code in one line, you can speed up the download, note that the speed of the download is not the speed of resolution, if it is local, comments and spaces do not affect the interpretation and execution speed.
Summary: It's faster to take something out of the box, such as a local variable faster than a global variable, a direct amount faster than a run-time object, and so on. Reduce the number of executions as little as possible, such as caching requires multiple queries first. Use language built-in features, such as String links, whenever possible. Use the system-provided APIs whenever possible, because these APIs are compiled binaries that are highly efficient to perform. At the same time, some basic algorithm optimization, also can be used in JavaScript, such as the adjustment of the operation structure, here will not repeat.
Because JavaScript is interpreted, it is generally not optimized for bytecode at run time, so these optimizations are still important.
JavaScript execution efficiency and performance Improvement Program (RPM)