How to improve JavaScript execution efficiency and performance is a very important place in front-end development. This section will study how to improve JavaScript performance and operating efficiency during daily project work.
Loop
Loop is a very commonly used control structure. Most things rely on it to complete. In JavaScript, we can use for(;;), while() , for (in) three kinds of loops, in fact, the efficiency of for (in) among these three kinds of loops is extremely poor, because it needs to query the hash key, so it should be used as little as possible as long as possible. The performance of for(;;) and while loop should be said to be basically equivalent (when used in daily use).
In fact, how to use these two loops is very particular. The final conclusion is:
If the loop variable is incrementing or decrementing, do not assign a value to the loop variable alone. You should use the nested or -- operator when it is read for the last time. If you want to compare with the length of the array, you should put the length attribute of the array into a local variable in advance to reduce the number of queries. For example, assuming arr is an array, the best way to traverse elements is:
for(var i=0, len = arr.length;i
Or, if the order doesn’t matter:
for(var i=arr.length;i>0;i--){...}
Local variables and global variables
Local variables are accessed faster than global variables, because global variables are actually members of the global object, and local variables are placed on the stack of the function.
Do not use Eval
Using eval is equivalent to calling the interpretation engine again to run the content at runtime, which takes a lot of time. At this time, the function template can be implemented using closures supported by JavaScript ( For the content of closures, please refer to the relevant content of functional programming)
Reduce object search
Because of the interpretability of JavaScript, a.b.c.d.e, at least 4 query operations are required. First check a, then check b in a, then check c in b, and so on. So if such an expression occurs repeatedly, you should try to minimize such expressions as much as possible. You can use local variables to put it. Enter a temporary place for querying. This can be combined with looping, because we often need to loop based on the length of strings and arrays, and usually the length is unchanged. For example, each time we query a.length, we need to add additional loops. To perform an operation and set var len=a.length in advance, there will be one less query.
String connection
If you are appending a string, it is best to use s =. anotherStr operation, instead of using s=s anotherStr. If you want to connect multiple strings, you should use less =, such as s =a;s =b;s =c; you should write s =a b c; and if you want to collect strings, you should use = less. , for example, if you perform = operations on the same string multiple times, it is best to use a cache. How to use it? Use JavaScript arrays to collect, and finally use the join method to connect them, as follows var buf = new Array();for(var i = 0; i < 100; i ){ buf.push(i.toString());}var all = buf.join("""");
Type conversion
Type conversion is a common mistake everyone makes, because JavaScript is a dynamically typed language and you cannot specify the type of a variable.
1. Convert numbers into strings and use """" 1. Although it looks a bit ugly, in fact this is the most efficient, in terms of performance:
("""" ) > String() > .toString() > new String()
This is actually somewhat similar to the "direct quantity" below. Try to use internal operations that can be used at compile time to be faster than user operations used at runtime.
String() is an internal function, so it is very fast, while .toString() needs to query the function in the prototype, so it is not as fast. new String() is used to return an exact copy.
2. Convert floating point numbers to integers. This is more error-prone. Many people like to use parseInt(). In fact, parseInt() is used to convert strings into numbers, not between floating point numbers and integers. To convert between, we should use Math.floor() or Math.round().
In addition, unlike the problem in object search in Section 2, Math is an internal object, so Math.floor() actually does not take much query method and calling time, and is the fastest.
3. For custom objects, if the toString() method is defined for type conversion, it is recommended to explicitly call toString(), because the internal operation will try the object after trying all possibilities. The toString() method tries to see if it can be converted into String, so calling this method directly will be more efficient.
Use direct quantities
In fact, this impact is relatively small and can be ignored. What does it mean to use direct quantities? For example, JavaScript supports using [param, param, param,...] to directly express an array. In the past, we all used new Array(param, param,...). Using the former is directly interpreted by the engine. , the latter calls an Array internal constructor, so it is slightly faster.
Similarly, var foo = {} is faster than var foo = new Object();, and var reg = /../; is faster than var reg=new RegExp().
String traversal operation
For loop operations on strings, such as replacement and search, regular expressions should be used, because the loop speed of JavaScript itself is relatively slow, and regular expressions The operation is a language API written in C, and the performance is very good.
Advanced Objects
Custom advanced objects and Date and RegExp objects consume a lot of time in construction. If it can be reused, caching should be used.
DOM related
Insert HTML
Many people like to use document.write in JavaScript to generate content for the 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 your own HTML code into the page.
Object query
Using [""""] query is faster than .items(). This is the same as the previous idea of reducing object search, calling .items () adds a query and function call.
Create DOM nodes
Usually we may use strings to write HTML directly to create nodes. In fact, doing so
cannot guarantee the validity of the code
String operation efficiency is low
So the document.createElement() method should be used. If there are ready-made template nodes in the document, the cloneNode() method should be used, because after using the createElement() method , you need to set the attributes of elements multiple times. Using cloneNode() can reduce the number of attribute settings - similarly, if you need to create many elements, you should prepare a template node first.
Timer
If you are targeting code that is constantly running, setTimeout should not be used, but setInterval should be used. setTimeout resets a timer each time.
Others
Script engine
According to my test, the efficiency of Microsoft's JScript is much worse than Mozilla's Spidermonkey, both in terms of execution speed and memory management, because JScript is now basically It is not updated either. But SpiderMonkey cannot use ActiveXObject.
File optimization
File optimization is also a very effective method. Delete all spaces and comments and put the code into one line to speed up the download. Note that it is a download The speed rather than the speed of parsing. If it is local, comments and spaces will not affect the speed of interpretation and execution.
Summary: It is faster to directly use ready-made things at hand. For example, local variables are faster than global variables, direct variables are faster than constructing objects at runtime, etc. Reduce the number of executions as much as possible, such as caching those that require multiple queries first. Use built-in language features, such as string concatenation, whenever possible. Use the APIs provided by the system as much as possible, because these APIs are compiled binary codes and have high execution efficiency. At the same time, some basic algorithm optimizations can also be used in JavaScript, such as adjustments to the calculation structure, which will not be described here.
Since JavaScript is interpreted, bytecode is generally not optimized at runtime, so these optimizations are still very important. If you are interested in how to improve the running speed of JavaScript, you can also check out other articles on this website about improving JavaScript performance.