getElementsByTagName和getElementById的效率问题 at 2008.11.11 8:08
虽然表面是 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: