首页 > 代码库 > 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效率高



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