JQuery for与each性能比较分析

时间:2022-10-27 21:32:45

话不多说,直接上demo:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery for与each性能比较分析</title>
</head>
<body>
<form id="form1" runat="server">
<div><select id="select_test">
<option value='1'>111111</option>
<option value='2'>222222</option>
<option value='3'>333333</option>
<option value='4'>444444</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
</select><input type="button" value="开始比较" onclick="getSelectLength();"/></div>
</form>
</body>
<script src="jquery-1.8.1.min.js"></script>
<script type="text/javascript" language="javascript">
function getSelectLength() {
var time1 = new Date().getTime();
var len = $("#select_test").find("option").length;
var selectObj = $("#select_test");
for (var i = 0; i < len; i++) {
if (selectObj.get(0).options[i].text == "111111") {
selectObj.get(0).options[i].selected = true;
break;
}
}
var time2 = new Date().getTime();
alert("for循环执行时间:" + (time2 - time1));
time1 = new Date().getTime();
$("#select_test").find("option").each(function () {
if ($(this).text() == "111111") {
$(this)[0].selected = true;
}
});
time2 = new Date().getTime();
alert("each循环执行时间:" + (time2 - time1));
}
</script>
</html>

  输出: 
    for循环执行时间:1 
    each循环执行时间:3 

 

如果不够明显,可以多copy一些option