SoFunction
Updated on 2025-04-09

Notes on JavaScript Script Performance Optimization

Loops are a very commonly used control structure, and most things need to be completed by relying on it. In JavaScript, we can use three loops: for(;;), while(), and for(in). In fact, the efficiency of for(in) in these three loops is extremely poor because it needs to query hash keys, and as long as it can, it should be used as little as possible. The performance of for(;;) and while loops should be said to be basically equivalent (when used normally).
In fact, there are great concerns about how to use these two loops. I have some interesting situations in the test, see the appendix. The final conclusion is:
If the loop variable is incremented or decreasing, do not assign values ​​to the loop variable alone. You should use the nested ++ or - operators when it was last read.
If you want to compare with the length of the array, you should put the length property of the array into a local variable in advance to reduce the number of queries.
Local and global variables
Local variables are faster than accessing global variables, because global variables are actually members of global objects, and local variables are placed in the function stack.
Don't use Eval
Using eval is equivalent to calling the interpretation engine again at runtime to run the content, which takes a lot of time. At this time, you can use the closures supported by JavaScript to implement function templates (for the content of closures, please refer to the relevant content of functional programming)
Reduce object search
Because of the explanatory nature of JavaScript, at least 4 query operations are required, first check a and then check b in a, then check c in b, and then continue. So if such an expression appears repeatedly, as long as possible, such expressions should be minimized. You can use local variables and put them in a temporary place for querying.
This can be combined with loops, because we often have to loop according to the length of strings and arrays, and usually this length is unchanged. For example, each query requires an additional operation, and var len= is used in advance, and one less query is required.
String connection
If you are appending a string, it is best to use s+=anotherStr instead of using s=s+anotherStr.
If you want to concatenate multiple strings, you should use less +=, such as
s+=a;s+=b;s+=c;
It should be written
s+=a + b + c;
If you are collecting strings, such as performing += operations on the same string multiple times, it is best to use a cache. How to use it? Use JavaScript array to collect it, and finally use the join method to connect it, as follows
var buf = new Array();for(var i = 0; i < 100; i++){ (());}var all = ("");
Type conversion
Type conversion is a common mistake for everyone, because JavaScript is a dynamic typed language and you cannot specify the type of a variable.
1. Convert numbers into strings and apply "" + 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 a bit similar to the "direct quantity" below. Try to use the internal operations that can be used during compilation and are faster than the user operations used during runtime.
String() is an internal function, so it is very fast, while .toString() needs to query the functions in the prototype, so it is less fast. New String() is used to return an exact copy.
2. Convert floating-point numbers to integers, which is more prone to errors. Many people like to use parseInt(). In fact, parseInt() is used to convert strings into numbers, rather than conversion between floating-point numbers and integers. We should use () or ().
In addition, unlike the problem in object search in Section 2, Math is an internal object, so () actually does not have much 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(), because the internal operations will try to see whether the object's toString() method can be converted into String after trying all possibilities, so it will be more efficient to call this method directly.
Use direct quantity
In fact, this impact is relatively small and can be ignored. What is the use of direct quantity? For example, JavaScript supports the use of [param,param,param,...] to directly express an array. In the past, we used new Array(param,param,...). The former is explained directly by the engine, and the latter requires an Array internal constructor, so it should be slightly faster.
Similarly, the method of var foo = {} is faster than var foo = new Object();, and var reg = /../; is faster than var reg=new RegExp().
String traversal operation
When performing loop operations on strings, such as replacement and search, regular expressions should be used, because JavaScript itself has slower looping speed, and regular expression operations are APIs written in C, and the performance is good.
Advanced Objects
Customized advanced objects, Date and RegExp objects will consume a lot of time when constructing. If reusable, cache should be used.
DOM related
Insert HTML
Many people like to use it in JavaScript to generate content for pages. In fact, this is inefficient. If you need to insert HTML directly, you can find a container element, such as specifying a div or span, and setting their innerHTML to insert your own HTML code into the page.
 Object query
Using [""] query is faster than .items(), which is the same as the previous idea of ​​reducing object search. Calling .items() adds a query and a call to function.
Create a DOM node
Usually we may use strings to write HTML to create nodes directly, but in fact, this is how to do it.
The validity of the code cannot be guaranteed
String operation efficiency is low
So you should use the() method. If there are ready-made boilerplate nodes in the document, you should use the cloneNode() method, because after using the createElement() method, you need to set the attributes of the element multiple times. Using cloneNode() can reduce the number of attributes set - similarly, if you need to create many elements, you should prepare a boilerplate node first.
Timer
If it is targeting code that is running continuously, you should not use setTimeout, but setInterval. setTimeout each time you want to reset a timer.
other
Script Engine
According to my test, Microsoft's JScript is much less efficient than Mozilla's Spidermonkey, both in terms of execution speed and memory management, because JScript is basically not updated now. But SpiderMonkey cannot use ActiveXObject
File Optimization
File optimization is also a very effective method. Deleting all spaces and comments and putting the code into one line can speed up the download speed. Note that it is the download speed rather than the parsing speed. If it is local, comments and spaces will not affect the interpretation and execution speed.
Summarize
This article summarizes some methods I found in JavaScript programming to improve the performance of JavaScript. In fact, these experiences are based on several principles:
It is faster to directly take things ready-made at hand, such as local variables faster than global variables, direct quantities faster than building objects at runtime, etc.
Reduce the number of executions as few as possible, such as cache the ones that require multiple queries first.
Use language built-in features, such as string linking, whenever possible.
Use the API provided by the system as much as possible, because these APIs are compiled binary code and have high execution efficiency.
At the same time, some basic algorithm optimizations can also be used in JavaScript, such as the adjustment of operation structure, which will not be described here. However, since JavaScript is interpreted and does not generally optimize the bytecode at runtime, these optimizations are still very important.
Of course, some of the techniques here are also used in some other interpreted languages, so you can also refer to them.