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 ('<p>' + I + '</P> ');
}
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 ('123 ');
}
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 (){
VaR El = Document. getelementbyid ('myelement ');
El. onclick = function (){......}
El = NULL;
}
Init ();
Leave el empty. The context does not contain references to DOM objects, thus interrupting the circular application.
To return the DOM object, use the following method:
Before taking:
Function Init (){
VaR El = Document. getelementbyid ('myelement ');
El. onclick = function (){......}
Return El;
}
Init ();
After taking:
Function Init (){
VaR El = Document. getelementbyid ('myelement ');
El. onclick = function (){......}
Try {
Return El;
} Finally {
El = NULL;
}
}
Init ();
2) construct a new context
Before taking:
Function Init (){
VaR El = Document. getelementbyid ('myelement ');
El. onclick = function (){......}
}
Init ();
After taking:
Function elclickhandler (){......}
Function Init (){
VaR El = Document. getelementbyid ('myelement ');
El. onclick = elclickhandler;
}
Init ();
Extract the function to the new context. In this way, the context of the function does not include a reference to El, thus interrupting the circular reference.
2.2 DOM objects created using JavaScript must be appended to the page
Note: In ie, the DOM object created by the script will not be recycled if it is not appended to the page and refreshed!
Sample Code:
Function create (){
VaR GC = Document. getelementbyid ('gc ');
For (VAR I = 0; I <5000; I ++)
{
VaR El = Document. createelement ('div ');
El. innerhtml = "test ";
// You can comment out the following sentence to see the memory changes after the browser clicks the button in the task manager.
GC. appendchild (EL );
}
}
2.3 release the memory occupied by DOM elements
Note:
Set innerhtml of the DOM element to an empty string to release the memory occupied by its child elements.
In rich applications, users may stay on a page for a long time. You can use this method to release the memory that has accumulated more and more DOM elements.
2.4 release JavaScript objects
Note: In rich applications, memory consumption increases as the number of instantiated objects increases. Therefore, the reference to the object should be released in time so that GC can recycle these memory controls.
Object: OBJ = NULL
Object Property: delete obj. myproperty
Array item: Use the splice method of the array to release unused items in the array.
2.5 avoid implicit packing of strings
Note: To Call The string method, such as 'xxx'. length, the browser will perform an implicit packing operation to convert the string into a string object first. We recommend that you use the following method to declare strings that may use the string instance method:
VaR mystring = new string ('Hello World ');