Let’s first take a look at the three algorithms and their performance under various browsers.
The first type: directly operate the dom.
table.border = 1;
var tbody = document.createElement("tbody");
var fragment = document.createDocumentFragment();
for(var i = 0; i < 1000; i ) {
var tr = document. createElement("tr");
for(var j = 0; j < 5; j ) {
var td = document.createElement("td");
td.appendChild(document.createTextNode ("cell " i "," j));
tr.appendChild(td);
}
fragment.appendChild(tr);
}
tbody.appendChild(fragment);
table.appendChild(tbody);
//chrome 0.03
//ie6 0.68
//ie7 0.43
//ie8 0.43
//ie9 0.37
// firefox14 0.03
//opera12 0.04
//safari5.17 0.023
document.body.appendChild(table);
var m2 = microtime(true);
alert(m2-m1) ;
第三种:借助js的原生表格操作方法
"http://www.w3.org/TR/html4/loose.dtd">
New Web Project
<script><br>microtime = function(get_as_float) {<br>var now = new Date().getTime() / 1000;<br>var s = parseInt(now, 10);<br>return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) ' ' s;<br>}<br>var m1 = microtime(true);<br>var table = document.createElement("table");<br>table.border = 1;<br>var tbody = document.createElement("tbody");<br>table.appendChild(tbody);<br>for(var i = 0; i < 1000; i ) {<BR>tbody.insertRow(i);<BR>for(var j = 0; j < 5; j ) {<BR>tbody.rows[i].insertCell(j);<BR>tbody.rows[i].cells[j].appendChild(document.createTextNode("cell " i "," j));<BR>}<BR>var tr = document.createElement("tr");<BR>tbody.appendChild(tr);<BR>}<BR>//chrome 0.19<BR>//ie9 0.18<BR>//ie8 0.25<BR>//ie7 8.50<BR>//ie6 20.45<BR>//firefox14 0.065<BR>//opera12 0.25<BR>//safari5.17 0.18<BR>document.body.appendChild(table);<BR>var m2 = microtime(true);<BR>alert(m2-m1);<BR></script>
以上可以看出用原生的js创建表格效率最好,借助createDocumentFragment优势不是很大(并不像网上说的那么明显),借助insertRow和insertCell等在ie6、7下效率太低,不建议使用。
对第一种算法简单的优化了一下:
"http://www.w3.org/TR/html4/loose.dtd">
New Web Project
<script><br>microtime = function(get_as_float) {<br> var now = new Date().getTime() / 1000;<br> var s = parseInt(now, 10);<br> return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) ' ' s;<br>}<br>var m1 = microtime(true);<br>var table = document.createElement("table");<br>table.border = 1;<br>var tbody = document.createElement("tbody");<br>var i = 1000;<br>while(i--){<br> var tr = document.createElement("tr"), j = 5;<br> while(j--){<br> var td = document.createElement("td");<br> td.appendChild(document.createTextNode("cell " i "," j));<br> tr.appendChild(td);<br> }<br> tbody.appendChild(tr);<br>}<br>table.appendChild(tbody);<br>//chrome 0.03<br>//ie6 0.66<br>//ie7 0.41<br>//ie8 0.41<br>//ie9 0.35<br>//firefox14 0.03<br>//opera12 0.03<br>//safari5.17 0.013<br>document.body.appendChild(table);<br>var m2 = microtime(true);<br>alert(m2-m1);<br></script>
总结:对dom操作尽量使用createElement和appendChild,对于js内核提供的一些特殊方法慎用。