首页 > 代码库 > JQuery for与each性能比较分析

JQuery for与each性能比较分析

话不多说,直接上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=http://www.mamicode.com/‘1‘>111111"button" value="http://www.mamicode.com/开始比较" onclick="getSelectLength();"/></div>
</form>
</body>
<script src="http://www.mamicode.com/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

JQuery for与each性能比较分析