Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

Is there any performance advantage to using the E#C CSS selector over #C?

I'm currently reading up on jQuery to fill some gaps in knowledge.

Looking at the various CSS selectors, I see:-

I know specificity is a big deal in the application of CSS rules, but given that it is bad practice to have duplicate IDs on a page, I'm wondering why the second form exists and how it is treated in jQuery.

Does it confer a performance advantage when interrogating the DOM? ( i.e. immediately limiting the scope of the selection ). This question applies mostly to jQuery, but I'd also be interested to know if it had any bearing on rendering engines, etc.

Upvotes: 0

Views: 63

Answers (2)

Jon
Jon

Reputation: 437554

jQuery has a specialized "fast path" to handle selectors of the form #C with a direct document.getElementById. Selectors of the form E#C are not handled by this path and are instead delegated to the Sizzle library.

Therefore I don't see how E#C could offer any performance benefit in practice, while there's no argument for better performance in theory as well. Indeed, E#C is much slower; see the massive performance difference here¹.

That said, the E#C selector is of course more restrictive so the behavior of the two will be different no matter if the selection is done by jQuery or any other medium. Even so I have never ever used E#C (or seen it used); I can't think of any reason to reuse an id across different pages.


¹Admittedly in real life that selector won't run in a loop, so the performance difference is not going to matter.

Upvotes: 3

Justice Erolin
Justice Erolin

Reputation: 2879

jQuery uses a bottom up search. It starts at the last selector and filters up.

Example:

$('#id1 .class1 .class2') looks for all classes of class2, then filters that result for all classes with a parent of class1 and then filters that further with a parent with id of id1

$('#profile') and $('div#profile') are essentially the same, roughly fractions of ms. But it's good to know the performance benefits and how to appropriately traverse the DOM.

Upvotes: 2

Related Questions