Summary of js Performance Optimization for stb frontend Development

Source: Internet
Author: User

Summary of js Performance Optimization for stb frontend Development

Js Performance Optimization

Javascript is an interpreted language, and its performance cannot reach the level of C, C ++, and other compiling languages. However, there are still some ways to improve it.

1. Loop

In JavaScript, there are three types of loops: for (;), while (), and for (in. The efficiency of for (in) is very poor, because hash keys need to be queried during the for (in) execution. For (;) and while (), while loop efficiency is better than (;;).

2. Local and global variables

The access speed of local variables is faster, because global variables are actually members of global objects, and local variables are placed in the function stack.

3. Do not use eval

Using the eval function is equivalent to calling the interpretation engine again at runtime to interpret and run the content.

4. Reduce Object Search

Because of JavaScript features, the class is the expression a. B. c. d. e and requires at least four query operations. First, check whether a is in B of. Avoid such expressions and use local variables to put the final result to a temporary location for query.

This can be combined with loops. For example, for an array, We can first obtain its length var len = a. length

# In java, the size of the List loop is first given to a temporary variable

5. String connection

If it is an append string, it is best to use the s + = anotherStr operation instead of the s = s + ""

However, to connect multiple strings, use less + = For example:

Java code

S + =;

S + = B;

S + = c;

It should be written as s + = a + B + c;

To collect strings, for example, to collect strings, it is best to use a cache. The specific implementation idea is to use Javascript arrays to collect each string. It is best to use the join method to connect these strings, as shown in the following code:

Var buf = new Array ();

For (var I = 0; I <100; I ++ ){

Buf. push (I. toString ());

}

Var all = buf. join ("");

6. type conversion

Type conversion is prone to errors in JavaScript programming, because JavaScript is a dynamic type language, that is, a weak type language, and the specific type of the variable cannot be specified.

1. Convert the number into a string and apply "" + 1. Although the number is awkward, the efficiency is the highest.

("" +)> String ()>. toString ()> newString ()

String () is an internal function, so the speed is very fast. toString () is used to query the function in the prototype, and new String () is used to return an exact copy.

2. Converting a floating point to an integer parseInt () is used to convert a string to a number. Math. floor () or Math. round () should be used to convert a floating point to an integer.

3. For custom objects, if the toString () method is defined for type conversion, we recommend that you call toString ()

7. Direct usage

In the past, we used new Array (parm, parm1.) and other forms. For direct interpretation, JavaScript supports the use of [param, param1....] to directly express an Array.

The previous method calls the internal constructor of Array, and the latter method is explained directly by the Interpretation engine, so the execution speed is slightly faster. Similarly, var foo = {} is faster than var foo = new Object (), and var reg =/.../is faster than var reg = new RegExp.

8. String Traversal

Use regular expressions first

9. Advanced object

Creating custom advanced objects, such as Date and RegExp, consumes a lot of time and resources.

10. insert HTML

Document. write is less efficient, and innerHTML is more efficient.

11. subscript Query

Using a direct subscript to search for an object is much faster than using the. name method.

12. Create a DOM Node

Generally, we may use strings to directly write HTML statements to create nodes. In fact, this has the following Disadvantages:

1. Code validity cannot be guaranteed;

2. Low string operation efficiency.

Use the exploreng. createElement () method. If an existing template node exists, use the cloneNode () method.

Therefore, the first principle is to optimize IE6 (the unpatched JScript 5.6 or earlier version!

If your program has been optimized to the acceptable performance in IE6, the performance will be no problem in other browsers.

Therefore, note that many of the problems I will discuss below may be completely different on other engines. For example, to concatenate strings in a loop, we usually think that Array is needed. but the SpiderMonkey and other engines have optimized the "+" Operation of the string, and the result is Array. instead, join is less efficient than directly using "+ "! However, if you consider IE6, the efficiency difference on other browsers is not worth mentioning.

JS optimization is still the same as optimization in other languages. For example, it makes no sense not to rush to optimize it as soon as it comes up. The key to optimization is to focus on the most critical aspect, that is, the bottleneck. In general, bottlenecks always occur in large cycles. This is not to say that the Loop itself has a performance problem, but that the loop will quickly enlarge the possible performance problems.

Therefore, the second principle is to optimize large-scale cyclic objects.

The following optimization principles make sense only in a large-scale loop. Such optimization outside the loop body is basically meaningless.

Currently, the vast majority of JS engines are interpreted and executed, while function calling is less efficient in all operations. In addition, a deep prototype inheritance chain or multi-level reference will also reduce the efficiency. In JScript, the overhead of level 10 references is roughly 1/2 of the overhead of an empty function call. The overhead of both is far greater than that of simple operations (such as the four arithmetic operations ).

Therefore, the third principle is to avoid too many reference levels and unnecessary multiple method calls.

In some cases, attribute access is actually a method call. For example, all DOM attributes are actually methods. When traversing a NodeList, the loop condition for nodes. length access seems to read the attribute, which is actually equivalent to the function call. In addition, in the implementation of ie dom, childNodes. length needs to be re-counted through internal traversal each time. (My god, but this is true! As I tested, the access time of childNodes. length is proportional to the value of childNodes. length !) This is very expensive. Therefore, saving nodes. length to js variables in advance can certainly improve the traversal performance.

Similarly, for function calls, the efficiency of user-defined functions is much lower than that of built-in functions, because the latter is the packaging of local engine methods, and the engine is usually c, c ++, written in java. Furthermore, for the same function, the overhead of built-in language construction is usually higher than that of built-in function calling, because the former can be determined and optimized in the parse stage of JS Code.

Therefore, the fourth principle is to use the constructor and built-in functions of the language as much as possible.

Here is an example of a high-performance String. format method. String. the traditional format implementation method is String. replace (regex, func) is called n times when pattern contains n placeholders (including repeated. In this high-performance implementation, each format call only performs an Array. join and then String. replace (regex, string) operations, both of which are built-in engine methods without any custom function calls. Two built-in method calls and n custom method calls are performance differences.

It is also a built-in feature, and the performance is still poor. For example, in JScript, the access performance to arguments is very poor, almost catching up with the callback function call. Therefore, if a simple function with a variable parameter becomes a performance bottleneck, you can make some internal changes. Instead of accessing arguments, you can handle it by explicitly determining the parameter.

For example:

Java code

Function sum (){

Varr = 0;

For (var I = 0; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

Function sum (){

Var r = 0;

For (var I = 0; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

This sum is usually called with a small number, and we hope to improve its performance when there are few parameters. If changed:

Java code

Function sum (){

Switch (arguments. length ){

Case 1: return arguments [0];

Case 2: return arguments [0] + arguments [1];

Case 3: return arguments [0] + arguments [1] + arguments [2];

Case 4: return arguments [0] + arguments [1] + arguments [2] + arguments [3];

Default:

Var r = 0;

For (var I = 0; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

}

Function sum (){

Switch (arguments. length ){

Case 1: return arguments [0];

Case 2: return arguments [0] + arguments [1];

Case 3: return arguments [0] + arguments [1] + arguments [2];

Case 4: return arguments [0] + arguments [1] + arguments [2] + arguments [3];

Default:

Var r = 0;

For (var I = 0; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

}

In fact, there will not be much improvement, but if it is changed:

Java code

Function sum (a, B, c, d, e, f, g ){

Var r =? B? C? D? E? F? A + B + c + d + e + f: a + B + c + d + e: a + B + c + d: a + B + c: a + B: a: 0;

If (g = undefined) return r;

For (var I = 6; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

Function sum (a, B, c, d, e, f, g ){

Var r =? B? C? D? E? F? A + B + c + d + e + f: a + B + c + d + e: a + B + c + d: a + B + c: a + B: a: 0;

If (g = undefined) return r;

For (var I = 6; I <arguments. length; I ++ ){

R + = arguments [I];

}

Return r;

}

It will increase a lot (at least one time faster ).

Finally, the fifth principle is often the most important performance obstacle in real applications, that is, to minimize unnecessary object creation.

Creating objects has a certain cost, but this cost is not big. The most fundamental problem is that as JScript's stupid garbage collection scheduling algorithm increases the number of objects, severe performance degradation (according to Microsoft, complexity is O (n ^ 2 )).

For example, our common String concatenation problem, after my tests and verification, simply creating string objects multiple times is actually not the cause of poor performance. What's terrible is the unnecessary garbage collection overhead during object creation. The Array. join method does not create an intermediate String object, which reduces the overhead of garbage collection.

Therefore, if we can convert large-scale object creation into a single statement, its performance will be greatly improved! For example, by constructing the code and then eval -- in fact, the PIES project is working on a specialized large-scale object generator based on this idea ......

The preceding figure shows the five JS optimization principles.

In addition to these principles, there are also some special cases, such as DOM traversal, which will be discussed later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.