I found a article regarding this a year ago but cannot find it now and all other articles I find aren't quite complete.
What I want is to build a definitive list of the quickest ways to select elements in jQuery
As Far as I understand it, If I had the following
<body>
<div id="container">
<ul class="count">
<li>One</li>
<li>Two</li>
<li class="selected">Three</li>
</ul>
</div>
</body>
In order of speed (fastest to slowest) Selecting by Id:
$('#container')
Select by Element:
$('div')
Select by class with help of element
$('ul.count')
Select by Part of Element Id with help of element (in this case ends with)
$("div[id$='tainer']")
Select by class
$('.count')
Select by Part of Element Id (in this case ends with)
$("[id$='tainer']")
Is this in the correct order of speed and have I missed any?
Thanks
performance of selectors depends on several things. browser is the main factor, with sizzle/querySelectorAll/jsengine, and jquery version which use them. Basically, jquery improves performances at each version, and does a good job to chose the best available method according to the browser.
Any kind of updates in the browser, js engine, or jquery itself can raise a new "best performer" method. Moreover, depending on the size and depth of the data a method can suddenly become faster than an other. And that's not to speak about the query itself. by example $('#id .class') might not use the same "engine" as $('#id').find('.class').
All in all, it's not a problem, jquery is quite optimized. When I stumble upon performance issues, it's quite never due to selectors (but to .append(), big , non delegated events or plugins, and overall: my plain old bad coding).
if you really, really need performance on the dom, you have to compare performance with 'document.getElementbyId' (when you have an id to use it with), and native 'document.querySelectorAll', which seems to be the fastest method of the month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With