日期:2014-05-17  浏览次数:20714 次

js innerhtml 与 creatElement 效率问题
 
<HTML> 
<HEAD> 
</HEAD> 
<BODY> 
<input type="button" value="测试1" onclick="test1()" /><input type=text readonly id=t1> 
<input type="button" value="测试2" onclick="test2()" /><input type=text readonly id=t2> 
<input type="button" value="清空" onclick="div1.innerHTML = ''; div2.innerHTML = ''; t1.value=''; t2.value = '';" /> 
<div id="div1"></div> 
<div id="div2"></div> 
</BODY> 
<script> 
function test1() 
{ 
var d = new Date(); 
var buf = new Array(); 
for (var n = 0; n < 1000; n ++) 
{ 
buf.push('<div onclick="alert(888);"><a href="">测试'); 
buf.push(n); 
buf.push('</a></div>'); 
} 
div1.innerHTML = buf.join(''); 
t1.value = '耗时:' + (new Date() - d); 
} 
function test2() 
{ 
var d = new Date(); 
for (var n = 0; n < 1000; n ++) 
{ 
var dd = document.createElement('a'); 
var e = document.createElement('a'); 
e.href = ''; 
e.innerText = '测试' + n; 
dd.appendChild(e); 
dd.onclick=function(){alert(999)}
div2.appendChild(dd); 
} 
t2.value = '耗时:' + (new Date() - d); 
} 
</script> 
</HTML> 



 
<HTML> 
<HEAD> 
</HEAD> 
<BODY> 
<input type="button" value="测试1" onclick="test1()" /><input type=text readonly id=t1> 
<input type="button" value="测试2" onclick="test2()" /><input type=text readonly id=t2> 
<input type="button" value="清空" onclick="div1.innerHTML = ''; div2.innerHTML = ''; t1.value=''; t2.value = '';" /> 
<div id="div1"></div> 
<div id="div2"></div> 
</BODY> 
<script> 
function test1() 
{ 
var d = new Date(); 
var buf = new Array(); 
for (var n = 0; n < 1000; n ++) 
{ 
buf.push('<a href="">测试'); 
buf.push(n); 
buf.push('</a>'); 
} 
div1.innerHTML = buf.join(''); 
t1.value = '耗时:' + (new Date() - d); 
} 
function test2() 
{ 
var d = new Date(); 
for (var n = 0; n < 1000; n ++) 
{ 
var e = document.createElement('a'); 
e.href = ''; 
e.innerText = '测试' + n; 
div2.appendChild(e); 
} 
t2.value = '耗时:' + (new Date() - d); 
} 
</script> 
</HTML> 

 
<HTML> 
<HEAD> 
</HEAD> 
<BODY> 
<input type="button" value="测试1" onclick="test1()" /><input type=text readonly id=t1> 
<input type="button" value="测试2" onclick="test2()" /><input type=text readonly id=t2> 
<input type="button" value="清空" onclick="div1.innerHTML = ''; div2.innerHTML = ''; t1.value=''; t2.value = '';" /> 
<div id="div1"></div> 
<div id="div2"></div> 
</BODY> 
<script> 
function test1() 
{ 
var d = new Date(); 
var buf = new Array(); 
for (var n = 0; n < 1000; n ++) 
{ 
buf.push('<a onclick="alert(888)" href="">测试'); 
buf.push(n); 
buf.push('</a>'); 
} 
div1.innerHTML = buf.join(''); 
t1.value = '耗时:' + (new Date() - d); 
} 
function test2() 
{ 
var d = new Date(); 
for (var n = 0; n < 1000; n ++) 
{ 
var e = document.createElement('a'); 
e.href = ''; 
e.innerText = '测试' + n; 
e.onclick=function(){alert(999)}
div2.appendChild(e); 
} 
t2.value = '耗时:' + (new Date() - d); 
} 
</script> 
</HTML> 



运行上面的例子后,你就知道了
innerHTML 比 createElement 快,它应该是JS内部优化过的,批量执行的(就像sql语句,批量要比一条条执行快很多)
但要注意:
1、不要用 "+=",这个耗内存和CPU
2、里面的标签一定要对应,否则会更慢或崩溃