[英]What is faster/more efficient/better when it comes to these $.each loops?
I have a Javascript object which looks like this: 我有一个看起来像这样的Javascript对象:
var a = {
b: [1,2,3,4,5,6,7,8,9],
c: [10,11,12,13,14,15]
}
to loop through both arrays (I want to loop through every value!) I use $.each
, but I can do this: 遍历两个数组(我想遍历每个值!)我使用
$.each
,但是我可以这样做:
// Option A:
$.each(a, function(i, d){
$.each(d, function(j, e){
console.log(e);
}
});
or this 或这个
// Option B:
$.each(a.b, function(k, f){
console.log(f)
})
$.each(a.c, function(l, g){
console.log(g)
})
Both generate exactly the same output, but which of these two versions is faster/more efficient/better? 两者都产生完全相同的输出,但是这两个版本中哪个更快/更有效/更好?
Is there any difference at all? 有什么区别吗?
Or is there a more faster/more efficient/better way (without $.each
)? 还是有更快,更高效/更好的方式(没有
$.each
)?
The most efficient way is to use a simple and native for
loop. 最有效的方法是使用简单的本机
for
循环。 Avoid jQuery at all. 完全避免使用jQuery。
Nothing can beat : 没有什么可以击败的:
var i=0, arr=a.b, len=arr.length;
for(; i<len; i++ ) { console.log(arr[i]) } ;
by the way, if you are in doubt, ask jsperf. 顺便说一句,如果您有疑问,请询问jsperf。
Here there's one test that shows a 5X / 10X increase : 这里有一个测试表明增加了5倍/ 10倍:
http://jsperf.com/for-vs-foreach/9 http://jsperf.com/for-vs-foreach/9
It is not true that using some kind of each
is always slower than a for loop. 这是不正确的使用某种
each
总是比for循环更慢。 SM and V8 can do pretty good inlining as long as you are not ruining it for them - a custom implementation of each taking advantage of the fact can run just as fast as a for loop . 只要您不破坏SM和V8的内联性,它们就可以很好地进行内联-利用它们的事实的自定义实现可以像for循环一样快地运行。
With that said, jQuery $.each
doesn't take advantage of the fact and it is slow. 话虽如此,jQuery
$.each
没有利用这一事实,而且速度很慢。 Avoid in performance sensitive situations. 避免在性能敏感的情况下使用。
As for your question, I expect the second one to be slightly faster in JITs because it avoids reflection and uses static property access which is taken advantage of by every modern engine. 关于您的问题,我希望第二个在JIT中更快一些,因为它避免了反射并使用了静态属性访问,每个现代引擎都利用了这种访问。 $.each is so slow that the difference isn't really pronounced here.
$ .each太慢了,以至于在这里并没有明显的区别。
http://jsperf.com/129031290419034 http://jsperf.com/129031290419034
If your real concern is speed then go for javascript's own for loop. 如果您真正关心的是速度,那么请使用javascript自己的for循环。 for your answer, I think Option b will be faster
为您的答案,我认为选项b会更快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.