Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selectors, efficiency

I have been reading more lately about the efficiency of the different selector engines. I know that jQuery uses the Sizzle engine and this blog post about some jQuery stuff mentioned that the Sizzle engine will break apart your selector into an array then parse left to right.

It then, from right to left, begins deciphering each item with regular expressions. What this also means is that the right-most part of your selector should be as specific as possible — for instance, an id or tag name.

My question is whether it is more efficient to run a selector with just the ID specified or the tag name as well:

var div = $('#someId');
//OR
var div = $('div#someId');

Since I write my CSS in the div#someId form I tend to do my selectors the same way, am I causing Sizzle to perform extra work (assuming QuerySelectorAll is unavailable)?

like image 598
Chad Avatar asked Aug 31 '11 19:08

Chad


People also ask

Which is the fastest selector in jQuery?

ID Selector: The jQuery #id selector selects the element on the basis of the ID attribute of the HTML tag. This selector is basically used when we have to work on a single element because an ID should be unique within a web page.

Which selector is faster in JavaScript?

Specifically, getElementById() and getElementsByClassName() are more than twice as fast as querySelector() and querySelectorAll() .

Does jQuery cache selector?

jQuery Sizzle does automatically cache the recent functions that have been created from the selectors in order to find DOM elements. However the elements themselves are not cached.


2 Answers

jQuery and Sizzle optimize the #id selector [source] to document.getElementById(id). I think they aren't able to optimize it like this with the tag#id.

The first is faster.

BTW specifying the tag name for an #id selector is over-specifying, as there can be only one tag with a given id on the document. Over-specifying is slower even in CSS.

like image 154
Arnaud Le Blanc Avatar answered Sep 29 '22 20:09

Arnaud Le Blanc


Rather than speculating, let's measure it!

Here's a test case with this page loaded, then matching a random element with both methods.

Make sure you scroll right down to the bottom.

http://jsperf.com/which-jquery-sizzle-selector-is-faster#runner

As you might expect, a plain id is faster than a tag qualified one (reduction to getElementByID). This is the same when using classes.

Selecting by ID is massively faster than selecting by class, mainly as IDs are guaranteed to be unique.

like image 25
Rich Bradshaw Avatar answered Sep 29 '22 20:09

Rich Bradshaw