SoFunction
Updated on 2025-04-06

JavaScript Learning Notes (17) js optimization

I have always been confused about why Situ Zhengmei still despises the following for loops,

for (var i = 0; i < ; i++) {

//Loop code

}

After reading the following article, I finally understood. . .

Language level

cycle

In JavaScript, we can use three loops: for(;;), while(), and for(in). In fact, for(in) in these three loops is extremely efficient because it needs to query the hash key, and as long as it can, it should be used as little as possible.

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.

So the above code should be written like this:

for (var i = 0,l = ; i < l; i++) {

//Loop code

}

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.

String connection

If you are collecting strings, such as performing += operation on the same string multiple times, it is best to use a cache. How to use it? Use JavaScript array to collect, and finally use the join method to connect, 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()

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. Therefore, 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.

same,var foo = {}The way is also better thanvar foo = new Object();quick,

var reg = /../;To comparevar reg=new RegExp()quick.

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, but in fact, this cannot guarantee the validity of the code.

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

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

Some methods to improve JavaScript running performance in JavaScript programming, in fact, these experiences are based on several principles:

1. 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.

2. Reduce the number of executions as few as possible, such as cache the ones that require multiple queries first.

3. Use built-in functions in the language as much as possible, such as string linking.

4. Use the APIs provided by the system as much as possible, because these APIs are compiled binary code and have high execution efficiency.

5. Some basic algorithm optimizations can also be used in JavaScript, such as adjustment of operation structure. 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.