STB Front-End Development JS Performance Optimization Summary

Source: Internet
Author: User
Tags eval garbage collection join javascript array

JS Performance optimization

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

1. Cycle

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

2, local variables and global variables

Local variables are accessed more quickly because global variables are actually members of global objects, and local variables are placed on the stack of functions.

3. Do not use eval

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

4. Reduce Object Lookup

Because of the nature of JavaScript, 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 check a, so down. You should try to avoid such an expression, you can use local variables to access the final results into a temporary location for the query.

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

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

5. String connection

If you are appending a string, it is best to use the S+=ANOTHERSTR action instead of using the s=s+ ""

But if you want to connect multiple strings, you should use + = For example:

Java code

S+=a;

S+=b;

S+=c;

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

If you are collecting strings, such as collecting strings, it is best to use a cache implementation. The idea is to use a JavaScript array 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 conversions are error-prone in JavaScript programming because JavaScript is a dynamic type language, a weakly typed language, and cannot specify the exact type of a variable.

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

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

String () is an intrinsic function, so it's fast, toString () to query the function in the prototype, the new string () is used to return an exact copy.

2, floating-point number conversion to integer parseint () used to convert strings to numbers, you should use Math.floor () or math.round () to achieve the conversion between floating-point and integral.

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

7, the use of direct quantity

In the past we used the new Array (Parm,parm1 ...) and other forms, for the interpretation of direct quantities 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 (), and Var reg=/..../is faster than Var reg=new RegExp ().

8, String traversal

Use regular Expressions preferentially

9. Advanced Object

Customizing advanced objects and Date, RegExp, and other object constructs consumes a lot of time and resources

10. Insert HTML

document.write efficiency is low, innerhtml efficiency is high

11, the Subscript query

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

12. Create a DOM node

In general, we may use strings to write HTML statements directly to create nodes, which in fact has the following drawbacks:

1, can not guarantee the validity of the code;

2, string operation efficiency is low.

You should use the Documeng.createelement () method. If there are ready-made boilerplate nodes, you should use the CloneNode () method.

So the first principle is that you just need to optimize for IE6 (a patch-only JScript 5.6 or earlier)!

If your program is optimized for performance that is acceptable under IE6, then basically the performance on the other browsers will be completely fine.

So, notice that many of the problems I'm talking about may be quite different on other engines, such as string concatenation in loops, which are often considered to be array.join, but because SpiderMonkey and other engines have optimized the "+" operations of strings, Results the use of array.join efficiency rather than directly with the "+"! But if you consider IE6, the difference in efficiency on other browsers is simply insignificant.

JS optimization and other language optimization still have the same place. For example, do not come up on the quick roar of the 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 loops. This is not to say that the loop itself has a performance problem, but a loop can quickly magnify possible performance problems.

So the second principle is to use large-scale circulation body as the most important optimization object.

The following optimization principles only make sense 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 to perform, and in the case of execution, function calls are less efficient in all operations. In addition, too deep prototype inheritance chains or multilevel 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 much 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 particularly noteworthy that in some cases it appears to be a property access, which is actually a method call. For example, the properties of all Dom are actually methods. When traversing a nodelist, cyclic conditions for nodes.length access, seemingly attribute reads, are actually equivalent to function calls. and the implementation of IE DOM, childnodes.length each time to be counted through the internal traversal. (My God, but this is true!) because I have measured, childnodes.length access time and childnodes.length value is proportional! This is very time-consuming. So in advance to save the nodes.length to the JS variable, of course, can improve the performance of traversal.

Also called function calls, user-defined functions are far less efficient than language-built functions, since the latter is a wrapper over the engine's local method, which is usually written by C,c++,java. Further, the same function, the cost of language construction is usually more efficient than the built-in function calls, because the former in the JS code in the parse phase can be identified and optimized.

So the fourth principle is to use the constructs and built-in functions of the language itself as much as possible.

Here's an example of a high-performance string.format approach. The traditional implementation of String.Format is to use String.Replace (Regex, func), when the pattern contains n placeholders (including duplicates), the custom function func is called n times. In this high-performance implementation, each format call does just one array.join and then one string.replace (regex, String) operation, both of which are engine-built methods without any custom function calls. Two-time built-in method calls and N-time custom method calls, which is the difference in performance.

There is also a difference in performance on the built-in features. For example, the access performance for arguments in JScript is poor, almost catching up with a function call. So if a simple function of a variable parameter becomes a performance bottleneck, you can make some changes within it, not accessing the 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 times, and we want to improve its performance when the parameters are less. If changed 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;

}

}

It's not going to be much better, but if you change it:

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 hurdle in real-world applications, is to minimize unnecessary object creation.

There is a certain cost to creating the object itself, but the price is actually not big. The most fundamental problem is that JScript's stupid garbage collection scheduling algorithm causes a severe drop in performance as the number of objects increases (according to Microsoft, the complexity is O (n^2)).

For example, our common string concatenation problem, after my test verification, simple to create string objects more than the reason is not poor performance. What's killing you 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 ...

All right, here's the Five Principles of JS optimization that I've summed up.

In addition to these principles, there are special cases, such as the DOM traversal, and later have time to do the discussion.

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.