<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>for與each性能比較</title> </head> <body><div id="test"></div> <input type="button" value="for" o ...
<!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>