I\'m not sure whether to use :first or :eq(0) in a selector. I\'m pretty sure that they\'ll always return the same object, but is one speedier than the other?
I\'m
2018: Yes, :first
and :eq(0)
return the same result although the performance difference would be marginal and perhaps even trivial in 2018.
2010: Good question and great post. I tested this some while ago and couldn't remember the exact outcome. I'm really glad to have found this because it's precisely what I was looking for.
I would guess that the reason for :first
and :eq(0)
being a tad slower is most likely related to parsing performance. Omitting these allows the jQuery engine to utilize the native getElementsByTagName
and getElementsByClassName
functions.
No surprises i.t.o. the DOM element being the fastest to access. Wrapping the DOM element with jQuery in a for loop won't necessarily have an adverse effect on performance as jQuery makes use of an expando property for caching purposes.
However, it would be interesting to see how get(0)
compares with DOM element access and how the jQuery wrapping thereof fares against eq(0)
and the rest of the results.
According to jQuery's source code, .first() is just a convenience wrapper for .eq(0)
:
first: function() {
return this.eq( 0 );
},
Yes they are equivalent.
No they aren't likely to be significantly different (anything else is micro-optimization).