5

I'm reading a book and they show a couple of examples of how to select elements on the DOM, but they advise to always use Jquery trasversing methods over the selectors, for example if you have a list inside a div instead of using

$("#myList > li")

You should use

$("#myList").children("li")

Most of the time I use the first over the latter, the author says the 2nd is prefered and more efficient but he does not address why, can anyone explain the reason behind this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • If you're interested in performance, you shouldn't use jQuery at all. Use what is clearer to you. – Bergi Jun 04 '13 at 02:05
  • possible duplicate of [jQuery selector performance](http://stackoverflow.com/questions/1411143/jquery-selector-performance) – Bergi Jun 04 '13 at 02:11
  • 2
    [Read this](https://developers.google.com/speed/docs/best-practices/rendering?hl=fr-FR#UseEfficientCSSSelectors) `Child and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.` – Jonathan de M. Jun 04 '13 at 02:13

1 Answers1

5

I think the difference in performance in that particular case comes down to this:

document.querySelectorAll('#myList > li');
// VS
document.getElementById('myList').children;

And the performance test here: http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74

jQuery might check to see if it's a li given the selector but that's still going to be faster than querySelectorAll or Sizzle.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Interestingly in Opera the native selector is about 50% faster :-) – Bergi Jun 04 '13 at 02:24
  • 1
    The jsperf is not apples-to-apples, because it's not filtering the children by tag name. Doing that, it turns out that `querySelectorAll` is fastest. See revised jsperf. –  Jun 04 '13 at 02:39
  • Revised jsperf is at http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74/3. FWIW, it turns out that XPath (`document.evaluate`) is around five times slower than `querySelectorAll`. –  Jun 04 '13 at 02:53
  • @torazaburo: That's interesting. In any case all these performance tests are usually irrelevant, the performance hit is not something to worry about here, I just wanted to illustrate the difference. – elclanrs Jun 04 '13 at 03:10