47

Is using $("#vacations").find("li").last() is a better practice than $("#vacations li:last")?

Background and my thoughts:

I was playing with a nice interactive try jQuery tutorial and one of the tasks says:

As you are looking through your code, you notice that someone else is selecting the last vacation with: $("#vacations li:last"). You look at this and you think, "Traversal would make this way faster!" You should act on those thoughts, refactor this code to find the last li within #vacations using traversal instead.

Why would I think so? For me usage of selectors looks a bit higher level than traversing. In my mind when I am specifying a selector it is up to jQuery how to better get the single result I need (without need in returning interim results).

What is that extra overhead of using composite selectors? Is it because current implementation of selectors logic just parses the string and uses the traversal API? Is parsing a string that slow? Is there a chance that a future implementation will use that fact that it does not need to return interim results and will be faster than traversal?

2
  • 7
    Here is a jspref.com test run for you jsperf.com/is-jquery-traversal-preferred-over-selectors you can easily test is now in different browsers.
    – Peeyush
    Mar 5, 2013 at 15:00
  • Not posting a new answer because it is not that relevant, but to the developer, both are useful: you can make an initial selection with a selector (can be complex) saving the result to a jQuery object, then conditionally run code A or B, and then on A run one traversing method and on B run a different one. It is easier (and less error prone) than conditionally building up a string to select the correct element. Jan 14, 2017 at 4:36

2 Answers 2

21

There's no cut and dry answer to this, but with respect to the :last selector you're using, it's a proprietary extension to the Selectors API standard. Because of this, it isn't valid to use with the native .querySelectorAll method.

What Sizzle does is basically try to use your selector with .querySelectorAll, and if it throws an Exception due to an invalid selector, it'll default to a purely JavaScript based DOM selection/filtering.

This means including selectors like :last will cause you to not get the speed boost of DOM selection with native code.

Furthermore, there are optimizations included so that when your selector is very simple, like just an ID or an element name, the native getElementById and getElementsByTagName will be used, which are extremely fast; usually even faster than querySelectorAll.

And since the .last() method just grabs the last item in the collection instead of filtering all the items, which is what Sizzle filters normally do (at least they used to), that also will give a boost.

IMO, keep away from the proprietary stuff. Now that .querySelectorAll is pretty much ubiquitous, there are real advantages to only using standards-compliant selectors. Do any further filtering post DOM selection.


In the case of $("#vacations").find("li"), don't worry about the interim results. This will use getElementById followed by getElementsByTagName, and will be extremely fast.

If you're really super concerned about speed, reduce your usage of jQuery, and use the DOM directly.


You'll currently find notes in the docs for selectors like :last, that warn you about the performance loss:

Because :last is a jQuery extension and not part of the CSS specification, queries using :last cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :last to select elements, first select the elements using a pure CSS selector, then use .filter(":last").

But I'd disagree that .filter(":last") would be a good substitute. Much better would be methods like .last() that will target the element directly instead of filtering the set. I have a feeling that they just want people to keep using their non-standards-compliant selectors. IMO, you're better of just forgetting about them.

14

Here's a test for your setup: http://jsperf.com/andrey-s-jquery-traversal

Sizzle, jQuery's selector engine, parses the string with regex and tries to speed up very basic selectors by using getElementById and getElementsByTagName. If your selector is anything more complicated than #foo and img, it'll try to use querySelectorAll, which accepts only valid CSS selectors (no :radio, :eq, :checkbox or other jQuery-specific pseudo-selectors).

The selector string is both less readable and slower, so there's really no reason to use it.

By breaking the selector string up into simple chunks that Sizzle can parse quickly (#id and tagname), you're basically just chaining together calls to getElementById and getElementsByTagName, which is about as fast as you can get.

2
  • good one, so $("#my_table").find("tr") is much better that $("#my_table tr") if i am not misunderstood and if we have 3 selectors needed we can chain them like $().find().find() and still benefit the js engine on the current client. Mar 3, 2016 at 13:59
  • @vtz: Time it. I don't think it'd be faster in that specific case.
    – Blender
    Mar 5, 2016 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.