论坛首页 Web前端技术论坛

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

浏览 4083 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-02-07  

首先先上模拟代码

 

<!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。

 

   发表时间:2014-02-09  
很正常。jquery要兼容多种浏览器,肯定需要做多个中间层,效率上相对于原生的代码会慢一些。就好比jvm的代码,再怎么写,也得经过JVM这一层,与原生的直接汇编来表示,效率也是可想而知的。
与此如此的讨论,还不如讨论一下,为什么同样的原生代码,在各浏览器间差异性是为什么?这估计更有意义些。
0 请登录后投票
   发表时间:2014-02-09  
freezingsky 写道
很正常。jquery要兼容多种浏览器,肯定需要做多个中间层,效率上相对于原生的代码会慢一些。就好比jvm的代码,再怎么写,也得经过JVM这一层,与原生的直接汇编来表示,效率也是可想而知的。
与此如此的讨论,还不如讨论一下,为什么同样的原生代码,在各浏览器间差异性是为什么?这估计更有意义些。


小伙,你能看懂我的文章吗?为什么慢我已经写了。另外,你觉得这是中间层吗?我用jq的包了吗?
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics