Which selector is faster?
29 SepIf you have any concerns about performance of your web application, you probably should read this. Some times ago i read on a site (don’t remember which, was like AGES ago) that a good performance improvement is to be VERY specific when you use a library to select an element from the DOM. That article was written with Prototype in mind but i’ve though that will work same for jQuery as well. HUGE MISTAKE!
Kinda obviously, jQuery is NOT Prototype and they seems to NOT work in the same manner. Today i think to test the results of various selector. For this, i used Profiler from Firebug (what? you don’t know what firebug is?). And i was amazed. And i mean AMAZED!
I made this test right on this blog. I used jQuery('li') in console and, after that i used jQuery('ul li') (there is 24 LI elements on the first page). Until today i think the second option is faster. Why? Well.. Is more specific, isn’t it?
The second pick is around 2.6 times SLOWER than first one. (0.533ms vs 0.205ms).
Unfortunately, i’ve try to use the slower technique on many projects. But, lucky me, for no reason, i always forgot to do that (and i use to remember too late)
So, be careful! Don’t make this mistake
If somebody will tell ya that a method is faster, DON’T take his word as a law. TEST IT!


[...] Ionut a récemment publié un article dans lequel il revient sur une “grosse erreur” dans la considération des performances [...]
I think it’s slower because it looks for all ul elements and after this looks again for all child li elements. So it takes to search attemps and not just one (but you can be shure all li’s are childs of ul).
I’ve seen so many debates on these issues recently while looking for something else, but the sad thing is, anyone that knows how javascript works, or understands the different offerings from the different browsers, will understand why there is no correct generic answer, or even browser or library specific answer on these topics, as every case is different.
“ul li” always slower than “li” because it has to run multiple searches for the same result set
“form.class” generally faster than “.class” because it can run getelementsbytagname first and greatly narrow down its result set. Depending on your browser and library, this difference may almost be reduced to 0 by the implementation of getelementsbyclassname that has been implemented natively in some browsers.
“form#id” slower than “#id” because you’re running more searches than required by a simple getelementbyid
These are all scenarios that I’ve seen people bring up as test cases for other scenarios and apply the “well this is faster so that must be faster” logic, without understanding what’s really going on…