for与each性能比较

时间:2021-08-15 08:33:50

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>for与each性能比较</title>
</head>
<body>
<div id="test"></div>
<input type="button" value="for" onclick="getFor();" />
<input type="button" value="each" onclick="getEach();" />
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" ></script>
<script type="text/javascript" language="javascript">
$(function(){
//加数据
for(var i=0;i<200;i++){
$("#test").append('<div class="test" title="">我就是测试</div>');
}

});
function getFor(){
var getclass = $(".test");
var length = getclass.length;
console.log(length);
var timestart = new Date().getTime();
for(var i=0;i<length;i++){
getclass[i].title = '我是for';
}
var timeend = new Date().getTime();
alert("for耗时:"+(timeend-timestart));
}
function getEach(){
var timestart = new Date().getTime();
$(".test").each(function(){
$(this).attr('title','我的each');
});
var timeend = new Date().getTime();
alert("each耗时:"+(timeend-timestart));

}
</script>

</body>
</html>

for与each性能比较

for与each性能比较