getElementsByTagName和getElementById的效率问题
虽然表面是 getElementById 消耗的时间应该比较短,但是自己始终不太相信,因为很多时候我不愿意给每个元素都添加 id,太费劲了,而更愿意使用 getElementsByTagName 来迭代。昨天花了一点时间,做了测试,首先对比一下遍历 20 个节点的速度:
getElementById:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>getElementById</title>
<script type="text/javascript">
function getS() {
var t1 = new Date();
if(document.getElementById("heheli")) var t2 = new Date();
alert(t2.getTime() - t1.getTime());
}
</script>
</head>
<body>
<ul>
<li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li id="heheli">5555555555555</li>
</ul>
<a href="#" onclick="getS();return false;">检测速度</a>
</body>
</html>
getElementsByTagName:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>getElementsByTagName</title>
<script type="text/javascript">
function getS() {
var t1 = new Date();
var lis = document.getElementsByTagName("li");
for(var i=0; i<lis.length; i++) {
if(lis[i].id == "heheli") {
var t2 = new Date();
alert(t2.getTime() - t1.getTime());
}
}
}
</script>
</head>
<body>
<ul>
<li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li>5555555555555</li> <li id="heheli">5555555555555</li>
</ul>
<a href="#" onclick="getS();return false;">检测速度</a>
</body>
</html>
各位可以运行以上两段代码,getElementById 平均消耗时间是 0 毫秒,getElementsByTagName 平均消耗时间是 1 毫秒,仅 1 毫秒之差。各位可以继续增加 li 的数量,我测试的当 li 的数量到 4000 左右的时候,getElementById 平均消耗时间在 6 毫秒,getElementsByTagName 平均消耗时间在 460 毫秒左右。
标签: getElementById, getElementsByTagName
这篇文章发布于 2008年11月11日,星期二,08:08,归类于 编码。 您可以跟踪这篇文章的评论通过 RSS 2.0 feed。 您可以留下评论,或者从您的站点trackback。