`
rainsilence
  • 浏览: 158770 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Jquery的each循环和原生循环及html5foreach循环的效率比较

 
阅读更多

首先先上模拟代码

 

<!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>Insert title here</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);
	}
}



var start = new Date().getTime();

var testNum = 3;

// each循环
each(result, function(item) {
	testNum += item;
});

var end = new Date().getTime();

// IE8下1530左右
console.log(end - start);
start = new Date().getTime();
testNum = 3;

// normal循环
for (var index = 0, len = result.length; index < len; index++) {
	testNum += result[index];
}
end = new Date().getTime();

// IE8下450左右
console.log(end - start);

if (Array.prototype.forEach) {
	start = new Date().getTime();
	testNum = 3;
	result.forEach(function(item) {
		testNum += item;
	});
	end = new Date().getTime();
	
	// Chrome下60以上
	console.log(end - start);
}



</script>


</head>
<body>

</body>
</html>

 

由于Firefox实在是太快了,所以将900000改成11900000,提高两个数量级。得出的结果是

jquery each:42

native loop:41

html5 foreach:40

 

在chrome下,11900000次循环

jquery each:260

native loop:92

html5 foreach:771

 

在ie8下,900000次循环,降低两个数量级

jquery each:1530

native loop:450

html5 foreach:不支持

 

Why is this result?

从js的实现原理上说,每段function在执行的时候,都会生成一个active object和一个scope chain。

所有当前function内部包含的对象都会放入active object中。

比如function F() {var a = 1;}

这个a就被放入了当前active object中,并且将active object放入了scope chain的顶层,index为0

 

看下这个例子:

var a = 1;
function f1() {
      var b = 2;
      function f2() {
            var c = 3 + b + a;
      }
      f2();
}
f1();

 

 

当f2执行的时候,变量c像之前的那个例子那样被放入scope chain 的index0这个位置上,但是变量b却不是。浏览器要顺着scope chain往上找,到scope chain为1的那个位置找到了变量b。这条法则用在变量a上就变成了,要找到scope chain 的index=2的那个位置上才能找到变量a。

总结一句话:调用位于当前function越远的变量,浏览器调用越是慢。因为scope chain要历经多次遍历。

 

因此,由于jquery each循环在调用的时候比原生的loop多套了一层function。他的查找速度肯定比原生loop要慢。而firefox的原生forEach循环在内部做了优化,所以他的调用速度几乎和原生loop持平。但是可以看到,在chrome上,html5的原生foreach是最慢的。可能是因为内部多嵌套了几层function。

 

Conclusion

对于效率为首要目标的项目,务必要用native loop。

 

分享到:
评论
1 楼 sys234 2016-05-05  
[u][/u]

相关推荐

Global site tag (gtag.js) - Google Analytics