我编写了这段代码来对 jQuery 与 DOM 性能进行基准测试。每个浏览器的性能都不同,性能最差的 Firefox X25 运行速度较慢 jQuery。这是预期的行为吗?我没想到 jQuery 会产生如此大的影响。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script language="JavaScript" type="text/javascript">
$(function () {
var i=0;
var dtb = new Date();
while(i < 1000000)
{
var index = Math.floor(Math.random()*30);
i++;
var elem = document.getElementById('d'+index);
}
var dte = new Date();
alert(dte-dtb);
i=0;
var dtb2 = new Date();
var body = document.getElementById('cog');
while(i < 1000000)
{
var index = Math.floor(Math.random()*30);
i++;
var elem = body.childNodes[index];
}
var dte2 = new Date();
alert(dte2-dtb2);
i=0;
var dtb3 = new Date();
while(i < 1000000)
{
var index = Math.floor(Math.random()*30);
i++;
var $elem = $("#d"+index);
}
var dte3 = new Date();
alert(dte3-dtb3);
/////EDIT//////
///// Implemented an Array as suggested by Erik Reppen ////////
i = 0;
var idNames=new Array(30);
while(i<30){
idNames[i] = $("#d"+i);
i++;
}
i=0;
var dtb4 = new Date();
while(i < 1000000)
{
var index = Math.floor(Math.random()*30);
i++;
var $elem = idNames[index];
}
var dte4 = new Date();
alert(dte4-dtb4);
/////EDIT//////////////////////////////////////////////
});
</script>
</head>
<body id="cog">
<div id="d0">sdfkjjfgdfd@@@</div><div id="d1">sdffgdfd@@@</div><div id="d2">sddfgfd</div><div id="d3">sdasfd</div><div id="d4">swqedfd</div><div id="d5">sddfdsfd</div><div id="d6">sdfd</div><div id="d7">sdsdffd</div><div id="d8">sdfsdfd</div><div id="d9">sdfkjlkjd</div><div id="d10">sdm ,nfd</div><div id="d11">sdcxvfd</div><div id="d12">sdxzcmfd</div><div id="d13">shgjmdfd</div><div id="d14">sdfvcbd</div><div id="d15">sdf;k;d</div><div id="d16">sdjklfd</div><div id="d17">sd412fd</div><div id="d18">sdfkyhkd</div><div id="d19">sdasdfd</div><div id="d20">sdhdfgsfd</div><div id="d21">sdfdsad</div><div id="d22">sdasdfd</div><div id="d23">sddfgdffd</div><div id="d24">sdklugiffd</div><div id="d25">sddfsafd</div><div id="d26">sdfq21fd</div><div id="d27">42324sdfd</div><div id="d28">sdnhmjkgufksfd</div><div id="d29">sdqwefdLAST</div>
</body>
</html>