您的位置:首页 > Web前端 > JQuery

jquery中的each和传统for性能比较

2014-01-05 22:24 465 查看
最近闲着没事,试了试jquery中的each和传统for的性能比较,以前都是混着在用,想用什么就用什么,试了之后还是决定以后少用each了,为什么呢?下面的例子就能说明一切了:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>for与each性能比较</title>
<script src="jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">

$(function(){
//加数据
for(var i=0;i<1000;i++){
$("#ceshi").append('<div class="cece" title="">000</div>');
}

});
function csfor(){
var cc = $(".cece");
var length = cc.length;
var time1 = new Date().getTime();
for(var i=0;i<length;i++){
cc[i].title = 'hhh';
}
var time2 = new Date().getTime();
alert("for耗时:"+(time2-time1));
}
function cseach(){
var time3 = new Date().getTime();
$(".cece").each(function(){
$(this).attr('title','ggg');
});
var time4 = new Date().getTime();
alert("each耗时:"+(time4-time3));

}
</script>
</head>
<body>
<div>
<div id="ceshi"></div>
<input type="button" value="for" onclick="csfor();" />
<input type="button" value="each" onclick="cseach();" />
</div>
</body>
</html>

看了弹出结果之后,什么都明白了!!!



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息