今天同事說js的前端中for的效率比較高,自己不信,因爲我記得php中foreach的效率比for的效率高,然後自己做了一個測試,如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ceshi</title>
<script type="text/javascript">
var result = createData();
function createData() {
var result = [];
for (var index = 0; index < 900000; index++) {
result.push(index);
}
return result;
}
/**
* 模擬jquery的each循環
*/
function each(arr, fn) {
for (var index = 0, len = arr.length; index < len; index++) {
fn.call(null, arr[index], index, arr);
}
}
// each循環
var start = new Date().getTime();
var testNum = 3;
each(result, function(item) {
testNum += item;
});
var end = new Date().getTime();
console.log(end - start);
//each 結束
// for循環
start = new Date().getTime();
testNum = 3;
for (var index = 0, len = result.length; index < len; index++) {
testNum += result[index];
}
end = new Date().getTime();
console.log(end - start);
//for循環結束
//forEach循環
if (Array.prototype.forEach) {
start = new Date().getTime();
testNum = 3;
result.forEach(function(item) {
testNum += item;
});
end = new Date().getTime();
console.log(end - start);
}
//循環結束
</script>
</head>
<body>
</body>
</html>
jquery each:60
native loop:22
html5 foreach:151
在ie11下
jquery each:65
native loop:27
html5 foreach:98
可見js的for函數還是比jquery的each以及html5的foreach效率高