[英]Is $('.foo').eq(0) faster than $('.foo')?
Suppose I have a huge list of elements with a structure like: 假设我有大量的元素列表,其结构如下:
<div class="item">
<div class="header"></div>
<div class="body"></div>
<div class="meta"></div>
<div class="..."></div>
...
</div><!-- .item -->
I've already found an element and now I have to find, let's say, a '.body'. 我已经找到一个元素,现在我必须找到一个“ .body”。 What code will work faster: 哪些代码可以更快地工作:
$(el).find('.body')
or 要么
$(el).find('.body').eq(0)
In other words, will jQuery stop on the first found element or will it loop through all the elements first and only then it will return an element with a chosen index? 换句话说,jQuery将在找到的第一个元素上停止还是会首先循环遍历所有元素,然后才返回具有选定索引的元素?
This question is ridiculous. 这个问题太荒谬了。 "Is it faster if I add another function or if I leave it out of the equation?" “如果我添加另一个函数还是将其排除在等式之外,它会更快吗?” is basically what you're asking: 基本上就是您要问的:
$(el).find('.body')
is about 6-7 times faster: http://jsperf.com/to-eq-or-not-to-eq $(el).find('.body')
大约快6到7倍: http : //jsperf.com/to-eq-or-not-to-eq
Your second example will always be slower, because it only calls an additional method on a jQuery object that contains all the elements matching .body
. 您的第二个示例将总是比较慢,因为它仅对包含与.body
匹配的所有元素的jQuery对象调用附加方法。
The fastest way to get the first matching element is probably the :first selector: 获取第一个匹配元素的最快方法可能是:first选择器:
$(el).find(".body:first")
You could also spare one method call by using the context
argument to $() , but benchmarks reveal that's actually slower : 您还可以通过使用$()的context
参数来节省一个方法调用, 但是基准测试表明它实际上要慢一些 :
$(".body:first", el) // Slower, don't do that.
.eq(0)
is a method call on the object returned by $(el).find('.body')
. .eq(0)
是对$(el).find('.body')
返回的对象的方法调用。 It can't be faster then $(el).find('.body')
alone. $(el).find('.body')
就不可能更快。
They will nearly same as as .eq('0')
is called on the result of find('.body')
. 它们几乎与在find('.body')
的结果上调用.eq('0')
相同。 The second one is never faster. 第二个永远不会更快。
$(el).find('.body:first')
或$(el).find('.body.eq(0)')
在逻辑上会更快,因为(至少)它执行的函数调用较少
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.