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效率高



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值