4

It's my understanding that, in terms of selector speed, that #ID selectors are fastest, followed by element selectors, and then .class selectors.

I have always assumed that pseudo-class selectors and custom selectors (those in the form ':selector') are similar to .class selectors, but I realised that I'm just not sure.

I realise that this does depend on the complexity of the code within the pseudo-class/custom selector, so I guess I'd like to know the answer with this excluded as factor.

Any help would be appreciated.

Thanks.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 1
    I can't possibly imagine any code that slow you're thinking about optimizing *selectors*... – Adam Kiss Apr 16 '10 at 11:58
  • I would have thought that it was goal of plugin writers to have the most optimal code possible - They can't guarantee that pages their code is used in are efficent and well structured. Anyone with horrendous HTML will invariably blame the plugin in this case. Anyway, I'm not really wanting a debate on the merits of optimising selectors. Feel free to start a new quesion, and I'll be happy to respond there. – James Wiseman Apr 16 '10 at 12:06
  • Well, the #ID would make sense, as they should be unique; however, I haven't yet measured any statistically significant difference in performance (also, frameworks like jQuery intelligently cache the selector lookups). – Piskvor left the building Apr 16 '10 at 12:12
  • @Adam: It's evaluating the selectors where the jQuery library (or specifically the Sizzle engine) does a lot of the work. So, knowing what kind of selectors are fast can be cruical for the scalability of a plugin. – Guffa Apr 16 '10 at 12:14
  • @Guffa: In my (really subject, if you can prove i'm wrong, *please*, do so) opinion, most processing time is spent with operations once the elements are selected. or? – Adam Kiss Apr 16 '10 at 12:20
  • @Adam: The processing once the elements are found is mostly linear, i.e. it depends only on the elements actually found. It's the process of finding the elements that is sensetive to the complexity of the selector and the size of the document, as it potentially has to examine every single element in the page. – Guffa Apr 16 '10 at 13:12

1 Answers1

3

It all comes down to what methods in the DOM the Sizzle engine (which is what jQuery uses to evaluate the selectors) can use to find the elements.

It can use the getElementById and getElementsByTagName methods to quickly get elements for a specific id and for a specific tag name. After that it simply has to loop through all found elements and compare each one to the conditions created from the selector.

The methods in the DOM can be used on any element, and used in combination, so for example finding all div elements inside an element with a specific id is very fast.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005