这些主要是我一直在想的一些事情,也许有人能给我一些更多的洞察力,我也会分享我到目前为止注意到的东西!
First thing i've been wondering... is there any difference good or reason to use:
$('element').each(function (i, el) { });
-- versus --
$.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.
But more importantly I'm concerned with speed here
// As opposed to $.each() looping through a jQuery object
// -- 8x faster
for (var i = 0, $('.whatever').length; i < len; i++) {
$('.whatever')[i] // do stuff
}
如果你看一下这个100,你会发现速度上的差异基本上等同于他们中的任何一个,但更重要的是,我觉得always应该使用for()
个循环……
我只是单元测试(循环5个不同的场景函数,50000次),简单地循环一系列列表项,设置data-newAttr
,没什么特别的.
QUESTION :: I guess my biggest question is, why not always use 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?
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
只有我的两个儿子.:)