Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery speed when referencing objects and their descendants

With regards to speed and using resources, If i save the html of a page as a jquery object, such as:

var meHTML = $('html')

Should i then reference further objects as say

var someID = meHTML.find('#someID')

as opposed to

var someID = $('#someID')

Im sure its probably only minimal, but Im curious to find out what the differences may be.

Thanks in advance for any advice.

like image 238
noelmcg Avatar asked Dec 04 '25 11:12

noelmcg


1 Answers

If you take a look at the source for a $("#id") call, you can see they enhanced a single ID selector alot by directly using document.getElementById and setting the length of the set to 1 manually.

The source for .find, however, is more expensive since the selector is passed through to Sizzle. Moreover, it checks for duplicates in the resulting set for example, which isn't necessary with an ID. It will come down to a longer and slower code path.

So, $("#id") should be faster.

like image 89
pimvdb Avatar answered Dec 07 '25 01:12

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!