1. 程式人生 > >javascript中for、each以及foreach的效率對比

javascript中for、each以及foreach的效率對比

今天同事說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>
在chrome下
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效率高