Recently, I encountered a js efficiency issue about adding elements to the page.
Suppose we have the following page:
Copy codeThe Code is as follows: <HTML>
<HEAD>
</HEAD>
<BODY>
<Div id = "div1"> </div>
</BODY>
<Script>
// Script location
</Script>
</HTML>
Now, we want to add objects to div1. We all know that the following code can be used to add an element to a web page:
// Method 1
Div1.innerHTML = '<a href = ""> test </a> ';
Or:
// Method 2
Var a = document. createElement ('A ');
A. innertText = 'test ';
Div1.appendChild ();
I found an article about js efficiency on the Internet, which means that method 2 is highly efficient. The comparison code is as follows:Copy codeThe Code is as follows: // method 1
Function init (){
Var staDate = new Date ();
Var doc = Invalid invalid doc ument;
For (var I = 0; I <100; I ++ ){
Var str = "<div id = 'div _ '" + I + "'style = 'width: 100px; height: 20px; background-color: # eee '> test </div> ";
Container. innerHTML + = str;
}
Alert (new Date-staDate );
}
// Method 2
Function init (){
Var staDate = new Date ();
Var doc = Invalid invalid doc ument;
For (var I = 0; I <100; I ++ ){
Var oDiv = doc. createElement ("div ");
Var oText = doc. createTextNode ("text ");
ODiv. appendChild (oText );
Container. appendChild (oDiv );
ODiv. style. id = "div _" + I;
ODiv. style. width = "100px ";
ODiv. style. height = "20px ";
ODiv. style. backgroundColor = "# eee ";
}
Alert (new Date-staDate );
}
The page contains:
<Div id = "container"> </div>
<Input type = "button" value = "start" onclick = "init ();"/>
From the execution result, solution 2 is about 10 times faster than solution 1. Is this true? In fact, the above test code is open to question, and the Circular code in method 1 is as follows:Copy codeThe Code is as follows: for (var I = 0; I <100; I ++ ){
Var str = "<div id = 'div _ '" + I + "'style = 'width: 100px; height: 20px; background-color: # eee '> test </div> ";
Container. innerHTML + = str;
}
There are many string operations, and in addition to using the + number to connect strings, The + = operator is also used, which is the problem, in javascript, this string operation seriously affects efficiency. Therefore, using the above method to test the efficiency of createEmenent and innerHTML is unfair to innerHTML, according to this, it is likely that string operations have eaten the performance of innerHTML, so I wrote the following test code:<Input type = "button" value = "Test 1" onclick = "test1 () "> <input type =" text "readonly id =" t1 "> <input type =" button "value =" Test 2 "onclick =" test2 () "> <input type =" text "readonly id =" t2 "> <input type =" button "value =" clear "onclick =" div1.innerHTML = ''; div2.innerHTML = ''; t1.value =''; t2.value = '';"> <p>