Javascript $.each() 与 for() 循环 - 和性能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11887450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$.each() vs for() loop - and performance
提问by Mark Pieszak - Trilon.io
These are mainly just some things I've been wondering, maybe someone can give me a little more insight on them, i'll share what i've noticed so far as well!
这些主要只是我一直想知道的一些事情,也许有人可以让我对它们有更多的了解,我也会分享我到目前为止所注意到的!
First thing i've been wondering... is there any difference good or reason to use:
我一直想知道的第一件事......是否有任何好处或使用理由:
$('element').each(function (i, el) { });
$('element').each(function (i, el) { });
-- versus --
- 相对 -
$.each($('element'), function (i, el) { });
$.each($('element'), function (i, el) { });
Looking at the jQuery docs I can't see any rhyme or reason for one or the other (maybe you know an instance or additional things one can do over the other.
查看 jQuery 文档,我看不到其中任何一个的任何押韵或原因(也许您知道一个实例或另一个可以做的其他事情。
But more importantly I'm concerned with speedhere
但更重要的是我关心这里的速度
// As opposed to $.each() looping through a jQuery object
// -- 8x faster
for (var i = 0, $('.whatever').length; i < len; i++) {
$('.whatever')[i] // do stuff
}
If you check out this jsFiddle DEMO here, you'll see the difference in speed is basically equivalent with either of them, but more importantly I feel like I should alwaysbe using for()
loops...
如果你在这里查看这个jsFiddle DEMO,你会发现速度上的差异基本上与它们中的任何一个相同,但更重要的是我觉得我应该总是使用for()
循环......
I was just unit testing (looping through each of 5 different scenario functions, 50,000 times), simply looping through a bunch of list items, and setting a data-newAttr
, nothing special.
我只是在进行单元测试(遍历 5 个不同的场景函数中的每一个,50,000 次),简单地遍历一堆列表项,并设置一个data-newAttr
,没什么特别的。
QUESTION :: I guess my biggest question is, why not alwaysuse for loops while iterating through an object?? Is there even a point to using $.each()? Do you always use for() loops even when going through jQuery objects?
问题 :: 我想我最大的问题是,为什么在遍历对象时不总是使用 for 循环?甚至有必要使用 $.each() 吗?即使在遍历 jQuery 对象时,您是否总是使用 for() 循环?
Function type: Execution Time:
_testArea.each() + $(this) 1947 <-- using $(this) slows it down tremendously
$.each() + $(this) 1940
_testArea.each() + el(plain JS) 458 <-- using the Element speeds things up
$.each() + el(plain JS) 452
for() loop + plainJS[0] iteration 236 <-- over 8x faster
Just my 2cents. :)
只是我的 2 美分。:)
采纳答案by Peter-Paul van Gemerden
One thing that .each()
allows you to do that can't be done with a for
loop is chaining.
.each()
允许您执行for
循环无法完成的一件事是链接。
$('.rows').each(function(i, el) {
// do something with ALL the rows
}).filter('.even').each(function(i, el) {
// do something with the even rows
});
I played around with your JSFiddleto see how chaining would influence performance in cases where you have to loop through subsets of the original set of matched elements.
我玩弄了您的JSFiddle,以了解在您必须遍历原始匹配元素集的子集的情况下,链接将如何影响性能。
The result wasn't all that unexpected, although I think the overhead of end()
was exaggerated here because of the combination of few elements and many loops. Other than that: plain JS loops are still slightly faster, but whether that weighs up to the added readability of .each()
(and chaining) is debatable.
结果并不是那么出人意料,尽管我认为end()
由于很少元素和许多循环的组合,这里的开销被夸大了。除此之外:普通的 JS 循环仍然稍微快一点,但这是否会影响.each()
(和链接)的可读性是有争议的。
回答by JayC
One thing you do get with .each()
is automatic local scoping (because you are invoking an anonymous function for every object), which in turn means if you are creating even more anonymous functions/closures/event handlers/whatever on every iteration, you never have to worry about your handlers sharing a variable. That is, JavaScript doesn't act like other languages when it comes to local scopes, but because you can declare a variable anywhere, it can fool you sometimes.
你得到的一件事.each()
是自动局部作用域(因为你正在为每个对象调用一个匿名函数),这反过来意味着如果你在每次迭代中创建更多的匿名函数/闭包/事件处理程序/任何东西,你永远不必担心您的处理程序共享变量。也就是说,当涉及到局部作用域时,JavaScript 的行为不像其他语言,但是因为你可以在任何地方声明一个变量,它有时会欺骗你。
In other words, this is wrong:
换句话说,这是错误的:
var idx,el;
for (idx = 0; idx <someObjectArray.length; idx++){
el = someObjectArray[idx]
el.someEventHandler(function(){
alert( "this is element " + idx);
});
}
Whenever any of those objects invoke their "someEvent" after this loop (please note that this is made up), the alert is always going to say whatever was last assigned to idx
, which should be (as of the time invoked) someObjectArray.length
;
每当这些对象中的任何一个在此循环之后调用它们的“someEvent”(请注意这是编造的),警报总是会说出最后分配给 的任何内容idx
,应该是(截至调用时间)someObjectArray.length
;
To make sure you save the proper index, you have to declare a local scope, create a variable and assign to that variable for use.
为了确保保存正确的索引,您必须声明一个局部作用域,创建一个变量并分配给该变量以供使用。
var idx,el;
for (idx = 0; idx <someObjectArray.length; idx++){
el = someObjectArray[idx];
(function(){
var localidx = idx;
el.someEventHandler(function(){
alert( "this is element " + localidx);
});
})();
}
As you can see, that's as ugly as hell, but it should work. Each event handler gets its own copy of localidx
正如你所看到的,这很丑陋,但它应该有效。每个事件处理程序都有自己的副本localidx
Now compare that to .each()
现在比较 .each()
$(someObjectArray).each(function (idx, el) {
el.someEventHandler(function(){
alert( "this is element " + idx);
});
});
A lot simpler, isn't it?
简单多了,不是吗?
回答by Yeti
jQuery.each vs for-loop
jQuery.each 与 for 循环
Advantages jQuery.each:
jQuery.each 的优点:
- Fits well in jQuery code (chaining and style).
- No worries about scope (references to the iterator and object will be persistent).
- Can be used universally (for all kinds of objects and iterating over object keys).
- 非常适合 jQuery 代码(链接和样式)。
- 不用担心范围(对迭代器和对象的引用将是持久的)。
- 可以普遍使用(用于各种对象和迭代对象键)。
Advantages for-loop:
for循环的优点:
- High performance (for games/animations/large datasets).
- Full control over iterator (skip items, splice items from list, etc).
- The for-loop will always work, for there is no dependency on jQuery.
- Same familiar syntax as most other similar languages.
- 高性能(用于游戏/动画/大型数据集)。
- 完全控制迭代器(跳过项目、从列表中拼接项目等)。
- for 循环将始终有效,因为不依赖于 jQuery。
- 与大多数其他类似语言相同的熟悉语法。
Example code
示例代码
This is example code of how I prefer to iterate over a list.
这是我更喜欢迭代列表的示例代码。
var list = ['a', 'b', 'c', 'd', 'e', 'f'];
jQuery.each:
jQuery.each:
$.each(list, function(i, v)
{
// code...
});
For-loop without closure:
没有闭包的for循环:
for(var i=0,v,n=list.length;i<n;i+=1)
{
v = list[i];
// code...
}
For-loop with closure:
带闭包的 for 循环:
for(var i=0,n=list.length;i<n;i+=1)
{
(function(i, v)
{
// code...
})(i, list[i]);
}
Note: I suggest you just use the standard for-loop, and only use a closure when necessary. However, when your code looks more like jQuery than Javascript anyway, it could be easier to just use $.each
. In case of performance issues, you could always look into it afterwards.
注意:我建议你只使用标准的 for 循环,并且只在必要时使用闭包。但是,当您的代码看起来更像 jQuery 而不是 Javascript 时,使用$.each
. 如果出现性能问题,您可以事后随时查看。
回答by op1ekun
I ran some simple performance test while ago http://jsperf.com/forloops3. Seems that sticking to plain, old for loop
(where it's possible) is the way to go :)
我之前运行了一些简单的性能测试http://jsperf.com/forloops3。似乎坚持简单,旧for loop
(可能的地方)是要走的路:)
回答by James Black
When I went to your link here are two numbers I got:
当我转到您的链接时,我得到了两个数字:
$.each() + el(plain JS) 401
for() loop + plainJS[0] iteration 377
If the difference is that small, then go with the one that is most readable, but, if you have very high time requirements, then you may just need to go with what ends up being the fastest.
如果差异很小,那么选择可读性最高的那个,但是,如果您有非常高的时间要求,那么您可能只需要选择最终最快的那个。
I would suggest you write your program to use three different methods, the two above, and then use the foreach found in newer versions of javascript, and for those browsers that don't support it you can add it as a prototype.
我建议您编写程序以使用三种不同的方法,上面两种,然后使用在较新版本的 javascript 中找到的 foreach,对于那些不支持它的浏览器,您可以将其添加为原型。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
You know what your requirements are, and what your program will do, so just write your own tests and ensure it meets the requirements across at the browsers you will be supporting.
您知道您的要求是什么,以及您的程序将要做什么,因此只需编写您自己的测试并确保它满足您将支持的浏览器的要求。
For your first question, I would go with $('element').each
as it is much easier to read, but that just my opinion.
对于你的第一个问题,我会同意,$('element').each
因为它更容易阅读,但这只是我的意见。
回答by ryanneufeld
Actually there is a big difference between $.each() and $().each().
实际上 $.each() 和 $().each() 之间有很大的区别。
They do slightly different things depending on what you're passing in.
根据您传入的内容,它们会做略有不同的事情。
http://api.jquery.com/each/vs http://api.jquery.com/jquery.each/
http://api.jquery.com/each/与http://api.jquery.com/jquery.each/
jquery.each is a generic iterator, where $().each() is specific to a jquery collection.
jquery.each 是一个通用迭代器,其中 $().each() 特定于 jquery 集合。