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'. 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?开发者_StackOverflow中文版
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
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
.
The fastest way to get the first matching element is probably the :first selector:
$(el).find(".body:first")
You could also spare one method call by using the context
argument to $(), but benchmarks reveal that's actually slower:
$(".body:first", el) // Slower, don't do that.
.eq(0)
is a method call on the object returned by $(el).find('.body')
. It can't be faster then $(el).find('.body')
alone.
They will nearly same as as .eq('0')
is called on the result of find('.body')
. The second one is never faster.
$(el).find('.body:first')
or $(el).find('.body.eq(0)')
would logically be faster, because (at least) it does execute less function calls
精彩评论