jquery的each和js原生for循环性能对比
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>for与each性能比较</title>
- <script src="../Cks/jquery-1.7.1.min.js" type="text/javascript"></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>
- </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>
- <div>
- </form>
- </body>
- </html>
输入出入:
for循环执行时间:1
each循环执行时间:3
两次结果直接说明了问题。