Summary of JS Performance optimization for STB front-end development

Source: Internet
Author: User

JS Performance Optimization

JavaScript is an interpreted language, with performance not reaching the level of compiled languages such as C and C + +, but there are some ways to improve it.

1. Circulation

The loop in JavaScript has a for (;;), while (), for (in) 3. Where for is inefficient because the hash key needs to be queried during the for execution. for (;;) Compared with while (), the while loop is more efficient than for (;;).

2. Local variables and global variables

Local variables are faster to access because global variables are actually members of global objects, and local variables are placed in the stack of functions.

3. Do not use eval

Using the Eval function is equivalent to invoking the interpretation engine again at run time to interpret the content to run

4. Reduce Object Lookup

Because of the JavaScript nature, for a class to be an expression a.b.c.d.e, you need at least 4 query operations. First, check A in the B in a, so down. You should try to avoid such expressions, and you can use local variables to put the final results you want to access into a temporary location for querying.

This can be combined with loops, for example, to an array that can fetch his length var len = a.length

# The loop for the list in the #其实java also takes the size to a temporary variable first

5. String Connection

If the string is appended, it is best to use the s+=anotherstr operation instead of s=s+ ""

However, if you want to concatenate multiple strings, you should use less than + = For example:

Java code

S+=a;

S+=b;

S+=c;

should be written s+=a+b+c;

If you are collecting strings, such as collecting strings, it is best to use a cache implementation. The practical idea is to use JavaScript arrays to collect each string, preferably using the Join method to concatenate the 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 a mistake in JavaScript programming because JavaScript is a dynamic type language, a weakly typed language, and cannot specify a specific type of variable.

1, the number into a string, the application "" +1, although more awkward, but the highest efficiency

("" +) >string () >.tostring () >newstring ()

String () is an intrinsic function, so fast, toString () queries the function in the prototype, and new string () is used to return an exact copy.

2, floating-point number conversion to Integer parseint () is used to convert a string to a number, you should use Math.floor () or math.round () to achieve the conversion between floating-point and integral type.

3, for custom objects, if the ToString () method is defined for type conversion, it is recommended to display the call ToString ()

7, the use of direct volume

In the past, we used the new Array (Parm,parm1.). and other forms, for the interpretation of direct volume JavaScript supports the use of [param,param1 ...] To express an array directly.

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

8. String Traversal

Preferential use of regular expressions

9. Advanced Objects

Custom high-level objects and date, RegExp, and other object constructs consume significant time and resources

10. Inserting HTML

document.write efficiency is low and innerhtml efficiency is high

11, subscript query

Using a direct subscript to find an object's properties is much faster than passing the. Name method.

12. Creating a DOM node

Often we may use strings to write HTML statements directly to create nodes, which in fact have the following drawbacks:

1, can not guarantee the validity of the code;

2, the string operation efficiency is low.

The Documeng.createelement () method should be used. If there are existing boilerplate nodes, the CloneNode () method should be used.

So the first principle is simply to optimize for IE6 (unpatched JScript 5.6 or earlier)!

If your program has been optimized for performance that is acceptable under IE6, there is basically no problem with performance on other browsers.

So, note that many of the issues that I'm talking about may be completely different on other engines, such as string concatenation in loops, which is usually thought to be array.join, but because the SpiderMonkey engine optimizes the "+" operation of Strings, As a result, the efficiency of using array.join is not as straightforward as "+"! But if you consider IE6, the difference in efficiency on other browsers is simply not worth mentioning.

JS optimization is still the same with other language optimizations. For example, do not get up on the quick roar to do optimization, so meaningless. The key to optimization is still to focus on the most critical place, that is, the bottleneck. In general, bottlenecks always occur in large-scale cycle locations. This is not to say that the loop itself has a performance problem, but that the loop will quickly magnify the possible performance issues.

So the second principle is to use large-scale cyclic body as the main optimization object.

The following optimization principles are only meaningful in a large-scale cycle, and it is essentially meaningless to do such optimizations outside of the loop body.

At present, most JS engines are interpreted, and in the case of interpretation execution, function calls are inefficient in all operations. In addition, too deep prototype inheritance chains or multi-level references can also reduce efficiency. In JScript, the overhead of a level 10 reference is roughly 1/2 of the cost of an empty function call. Both are far more expensive than simple operations (such as arithmetic).

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

It is especially important to note that in some cases it seems to be a property access, which is actually a method call. For example, all DOM properties are actually methods. When traversing a nodelist, the loop condition for nodes.length access, which looks like a property read, is actually equivalent to a function call. And the implementation of the IE DOM, childnodes.length each time to be re-counted through the internal traversal. (My God, but this is true!) Because I have measured, the access time of childnodes.length is proportional to the value of Childnodes.length! This is very expensive. Therefore, the pre-saving nodes.length to the JS variable, of course, can improve the performance of the traversal.

The same is true for function calls, where user-defined functions are much less efficient than language-built functions, because the latter is a wrapper on the local method of the engine, and the engine is usually written c,c++,java. Further, the same function, the overhead of building a language is usually more efficient than the built-in function call, because the former can be identified and optimized in the parse phase of the JS code.

So the fourth principle is to try to use the language itself and the built-in functions.

Here is an example of a high-performance String.Format method. The String.Format tradition is implemented using String.Replace (Regex, Func), where the custom function func is called n times when the pattern contains n placeholders (including duplicates). In this high-performance implementation, each format call is made only once array.join and then once String.Replace (Regex, String), both are built-in methods of the engine, without any custom function calls. Two times built-in method calls and N-Times custom method calls, which is the difference in performance.

As well as built-in features, there are also differences in performance. For example, in JScript, access to arguments is poor and almost catches up with a function call. So if a variable parameter's simple function becomes a performance bottleneck, you can make some changes inside it, instead of accessing arguments, but by explicitly judging the parameters.

Like what:

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 fewer numbers, and we want to improve its performance when there are fewer parameters. If you change to:

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 you change to:

Java code

function sum (A, B, C, D, E, F, g) {

var r = a? 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 = a? 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;

}

Will improve a lot (at least 1 time times faster).

Finally, the fifth principle, and often the most important performance barrier in real-world applications, is to minimize unnecessary object creation.

There is a cost to creating the object itself, but the cost is not very large. The fundamental problem is that because of the folly of JScript's garbage collection scheduling algorithm, the performance is severely degraded as the number of objects increases (according to Microsoft, the complexity is O (n^2)).

For example, our common string splicing problem, after my test to verify that the simple creation of string objects more than the reason for poor performance at all. The fatal is the overhead of unnecessary garbage collection during object creation. In the Array.join way, the intermediate string object is not created, thus reducing the cost of the damned garbage collection.

Therefore, if we can transform large-scale object creation into a single statement, its performance will be greatly improved! For example, by constructing code and then eval--actually Pies project is based on this idea to do a specialized large-scale object generator ...

Well, above is the sum of the JS optimization of the five main principles.

In addition to these principles, there are some special cases, such as the traversal of the DOM, and there is time to discuss it 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.