关于JavaScript中使用appendChild和innerHTML动态添加一个元素的时间的比较

来源:互联网 发布:cnrds 数据产品 编辑:程序博客网 时间:2024/06/05 20:27
关于JavaScript中使用appendChild和innerHTML动态添加一个元素的时间的比较
1.时间比较:
代码:
<pre name="code" class="html"><!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>时间测试</title><style>*{margin:0; padding:0;}div.con_left{width:300px; float:left; border:1px solid #a9a9a9; margin-left:50px;}div.con_right{width:300px; float:left; border:1px solid #a9a9a9; margin-left:50px;}.con_left ul{margin:0; padding:0; width:300px; text-align:center;}.con_left li{margin:0; padding:0; display:list-item; line-height:20px; list-style:none;}.con_right ul{margin:0; padding:0; width:300px; text-align:center;}.con_right li{margin:0; padding:0; display:list-item; line-height:20px; list-style:none;}</style></head><body><div class="con_left"><ul id="ul_left"></ul></div><div class="con_right"><ul id="ul_right"></ul></div><script type="text/javascript">var count = 10000;//下面循环次数var ul_left = document.getElementById("ul_left");var ul_right = document.getElementById("ul_right");var time_start1 = new Date();console.log("appendChild方式开始时间="+time_start1.getHours()+":"+time_start1.getMinutes()+":"+time_start1.getSeconds()+":"+time_start1.getMilliseconds());for(var i=0; i<count; i++){var a = document.createElement("a");var li = document.createElement("li");a.href = "#";a.innerHTML = "超链接"+(i+1);li.appendChild(a);ul_left.appendChild(li);}var time_end1 = new Date();console.log("appendChild方式结束时间="+time_end1.getHours()+":"+time_end1.getMinutes()+":"+time_end1.getSeconds()+":"+time_end1.getMilliseconds());var time_start2 = new Date();console.log("innerHTML方式开始时间="+time_start2.getHours()+":"+time_start2.getMinutes()+":"+time_start2.getSeconds()+":"+time_start2.getMilliseconds());for(var i=0; i<count; i++){var a = document.createElement("a");var li = document.createElement("li");li.innerHTML = "<a href='#'>超链接"+(i+1)+"</a>";ul_right.appendChild(li);}var time_end2 = new Date();console.log("innerHTML方式结束时间="+time_end2.getHours()+":"+time_end2.getMinutes()+":"+time_end2.getSeconds()+":"+time_end2.getMilliseconds());</script></body></html>


结果1(Chrome):

结果2(FireFox):

结果3(IE):

总结果:
 appendChild方式innerHTML方式Chrome(循环10万次)823ms1162msFireFox(循环10万次)650ms1266msIE(循环1万次)3480ms5485ms
结论:(感觉我的电脑配置还行,i5的处理器,8G的内存,但是IE浏览器中循环10万次的时候卡的不出结果,所以只能设置1万次了)appendChild方式明显要比innerHTML方式速度快。


0 0
原创粉丝点击