I’m trying to find a definitive answer to the old question “should i use a tag name when selecting with a class?”
Everywhere i look on the web for jQuery best practices, there is nearly always a point of using jQuery(“tag.className”); because this uses getElementByTagName first.
So I’ve set up a benchmark on jsPerf to check. I’ve used the source markup from my website so its more of a real world test and run the benchmark on all modern browsers and apart from Chrome and Opera, all the other modern browsers say that jQuery(“.className”); is an order of magnitude faster even though this goes against nearly everything i’ve read in books and tutorials online. I assume its faster because those browsers support getElementByClassName natively.
Here’s the benchmark:
http://jsperf.com/length-detection
What do you think is best?
Many thanks
Chris
If you are really after performance, you should not use jQuery at all for querying elements. See this jsperf: http://jsperf.com/jquery-selecting-by-class
There we can talk about “magnitudes”. Honestly, without looking into the current jQuery source I can’t tell what jQuery does under the hood. Even if it’s using
getElementsByClassNamesit will have little and zero effect on overall performance due to all the blood and overhead that comes along jQuery. Anyway, the basic rule for querying elements is simple: Don’t be overspecific. CSS Selectors work from right to left, so when we have a query likeelement.classname, most engines will first grab all elements with the classname ofclassnameand then filter out the nodes which also belong the to element type ofelement.