Just interested, which one’s faster? Couldn’t google it up.
For example, $('li:first') vs $('li').first()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: apparently the parsing of the expression incurs a lot of overhead.
In my quick benchmark
.first()is a lot faster than using the selector.Expressions simply boil down to methods on the $.expr object like explained here
The actual implementation of the :first vs the .first() differ a bit:
Here the code for :first on
$.expr.setFilters.firstwhile
$.fn.firstis simply a shorthand for.eq(0):without looking at the actual code I’d implement a first() like this if it wasn’t there:
This also means that :first is simply a filter on a list of elements, while .first() is a reduce operation that’s more efficient.
Update2: Doh – Should have read the docs. Since jQuery tries to use native CSS selectors in modern browsers and
:firstis no selector from the CSS spec it will always perform a lot worse than a real selector that can take advantage of the browsers native CSS searching methods (whereas jQuery has to emulate that behavior in JS)