Considerations for improving Javascript Performance

Source: Internet
Author: User
Recently, my js Code is messy. Why should I write it. execution efficiency 1. DOM1.1 use DocumentFragment to optimize multiple append operations: when multiple dom elements are added, the elements are first appended to DocumentFragment, and finally added to the page. This practice can be reduced

The js Code I wrote recently Seems messy. Why should I write it?

1. execution efficiency
1. DOM
1.1 Use DocumentFragment to optimize multiple appends
Note: When multiple dom elements are added, append the elements to DocumentFragment and add DocumentFragment to the page.
This method can reduce the number of times dom elements are rendered on a page. In IE and Fx tests, the efficiency of append1000 elements can be improved by 10%-30%, while that of Fx is more obvious.

Before taking:
For (var I = 0; I <1000; I ++ ){
Var el = document. createElement ('P ');
El. innerHTML = I;
Document. body. appendChild (el );
}

After taking:
Var frag = document. createDocumentFragment ();
For (var I = 0; I <1000; I ++ ){
Var el = document. createElement ('P ');
El. innerHTML = I;
Frag. appendChild (el );
}
Document. body. appendChild (frag );

1.2 replace createElement with template element clone
Note: using a template dom object cloneNode is more efficient than directly creating an element.
Performance improvement is not significant, about 10%. There is no advantage in the create and append operations of less than 100 elements.

Before taking:
Var frag = document. createDocumentFragment ();
For (var I = 0; I <1000; I ++ ){
Var el = document. createElement ('P ');
El. innerHTML = I;
Frag. appendChild (el );
}
Document. body. appendChild (frag );

After taking:
Var frag = document. createDocumentFragment ();
Var pEl = document. getElementsByTagName ('P') [0];
For (var I = 0; I <1000; I ++ ){
Var el = pEl. cloneNode (false );
El. innerHTML = I;
Frag. appendChild (el );
}
Document. body. appendChild (frag );

1.3 Use an innerHTML value assignment instead of building dom elements
Note: When creating a list style based on data, you can set the list container innerHTML to Improve the efficiency by an order of magnitude by building dom elements and appending them to the page.

Before taking:
Var frag = document. createDocumentFragment ();
For (var I = 0; I <1000; I ++ ){
Var el = document. createElement ('P ');
El. innerHTML = I;
Frag. appendChild (el );
}
Document. body. appendChild (frag );

After taking:
Var html = [];
For (var I = 0; I <1000; I ++ ){
Html. push ('

'+ I +'

');
}
Document. body. innerHTML = html. join (");

1.4 Use firstChild and nextSibling instead of childNodes to traverse dom elements
Note: The performance can be improved by about 30%-50%. LastChild and previussibling are used for reverse traversal.

Before taking:
Var nodes = element. childNodes;
For (var I = 0, l = nodes. length; I <l; I ++ ){
Var node = nodes [I];
......
}

After taking:
Var node = element. firstChild;
While (node ){
......
Node = node. nextSibling;
}

2. String

2.1 use Array as the StringBuffer to replace String concatenation operations
Note: During String concatenation, IE creates a temporary String object. After testing, in IE, when the concatenated String grows larger, the running efficiency decreases sharply. Both Fx and Opera have optimized the String concatenation operation. After testing, in Fx, the execution time of the join method using Array is about 1.4 times that of the direct String concatenation.

Before taking:
Var now = new Date ();
Var str = ";
For (var I = 0; I <10000; I ++ ){
Str + = '000000 ′;
}
Alert (new Date ()? Now );

After taking:
Var now = new Date ();
Var strBuffer = [];
For (var I = 0; I <10000; I ++ ){
StrBuffer. push ('000000 ′);
}
Var str = strBuffer. join (");
Alert (new Date ()? Now );

3. Loop statements

3.1 Save the cyclic control value to a local variable
Note: The length of the array and List objects is saved to a local variable in advance to avoid repeated values in each step of the loop.

Before taking:
Var list = document. getElementsByTagName ('P ');
For (var I = 0; I <list. length; I ++ ){
......
}

After taking:
Var list = document. getElementsByTagName ('P ');
For (var I = 0, l = list. length; I <l; I ++ ){
......
}

3.2 sequential irrelevant time, replaced by while
Note: This method can reduce the use of local variables. Compared with efficiency optimization, the number of characters is optimized. This practice is suspected of being obsessive-compulsive by programmers.

Before taking:
Var arr = [1, 2, 4, 5, 6, 7];
Var sum = 0;
For (var I = 0, l = arr. length; I <l; I ++ ){
Sum + = arr [I];
}

After taking:
Var arr = [1, 2, 4, 5, 6, 7];
Var sum = 0, l = arr. length;
While (l ?) {
Sum + = arr [l];
}

4. Condition Branch

4.1 sort the condition branches in ascending order of likelihood
Note: This reduces the number of times the interpreter detects conditions.

4.2 When multiple (> 2) condition branches under the same condition subscribe, switch is better than if
Note: switch Branch selection is more efficient than if, especially in IE. For a 4-branch test, the switch execution time in IE is about half of if.

4.3 use the three-object operator to replace the condition Branch
Before taking:
If (a> B ){
Num =;
} Else {
Num = B;
}

After taking:
Num = a> B? A: B;

5. Timer

5.1 When continuous execution is required, setInterval is preferred.
Note: setTimeout initializes a timer every time. SetInterval only initializes a timer at the beginning.

Before taking:
Var timeoutTimes = 0;
Function timeout (){
TimeoutTimes ++;
If (timeoutTimes <10 ){
SetTimeout (timeout, 10 );
}
}
Timeout ();

After taking:
Var intervalTimes = 0;
Function interval (){
IntervalTimes ++;
If (intervalTimes> = 10 ){
ClearInterval (interv );
}
}
Var interv = setInterval (interval, 10 );

5.2 use function instead of string
Note: If the string is used as the parameter of setTimeout and setInterval, the browser will use this string to construct a function.

Before taking:
Var num = 0;
SetTimeout ('num ++ ', 10 );

After taking:
Var num = 0;
Function addNum (){
Num ++;
}
SetTimeout (addNum, 10 );

6. Miscellaneous

6.1 try not to use dynamic syntax Elements
Note: statements such as eval, Function, and execScript are parsed using the javascript parsing engine again, which consumes a lot of execution time.

6.2 duplicate call results are saved to local variables in advance
Note: Avoid calling overhead for multiple values.

Before taking:
Var h1 = element1.clientHeight + num1;
Var h2 = element1.clientHeight + num2;

After taking:
Var eleHeight = element1.clientHeight;
Var h1 = eleHeight + num1;
Var h2 = eleHeight + num2;

6.3 direct usage
Note:
Var a = new Array (param, param ,...) -> Var a = []
Var foo = new Object ()-> var foo = {}
Var reg = new RegExp ()-> var reg = /... /

6.4 avoid using
Note: although with can shorten the amount of code, it will construct a new scope at runtime.
OperaDev has such an explanation. Using the with statement makes it impossible for the interpreter to optimize the code in the Syntax Parsing phase. This statement cannot be verified.

Before taking:
With (a. B. c. d ){
Property1 = 1;
Property2 = 2;
}

After taking:
Var obj = a. B. c. d;
Obj. property1 = 1;
Obj. property2 = 2;

6.5 clever use | and & boolean operators
Importance:★★★

Before taking:
Function eventHandler (e ){
If (! E) e = window. event;
}

After taking:
Function eventHandler (e ){
E = e | window. event;
}

Before taking:
If (myobj ){
DoSomething (myobj );
}

After taking:
Myobj & doSomething (myobj );

6.6 type conversion
Note:
1). Convert the number to a String and apply "" + 1. performance: ("" +)> String ()>. toString ()> new String ();
2 ). if you do not use parseInt () to convert a floating point to an integer, parseInt () is used to convert a string to a number, rather than between a floating point and an integer. We recommend that you use Math. floor () or Math. round ()
3) We recommend that you explicitly call toString () for custom objects (). After all the possibilities are attempted, the internal operation will try to convert the toString () method of the object to String.

Ii. Memory Management

2.1 circular references
Note: If the circular reference contains a DOM object or ActiveX object, memory leakage will occur. The consequence of Memory leakage is that, even if the page is refreshed before the browser is closed, the memory will not be released by the browser.

Simple loop reference:
Var el = document. getElementById ('myelement ');
Var func = function (){...}
El. func = func;
Func. element = el;

But this usually does not happen. Loop references usually occur when a closure is added to a dom element as an expendo.

For example:
Function init (){
Var el = document. getElementById ('myelement ');
El. onclick = function (){......}
}
Init ();

During init execution, the current context is called context. At this time, context references el, el references function, and function references context. At this time, a circular reference is formed.

The following two methods can solve the problem of loop reference:

1) Empty dom object

Before taking:
Function init (){
Var el = document. getElementById ('myelement ');
El. onclick = function (){......}
}
Init ();

After taking:
Function init () {<

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.