What is the cost of finding a node in jQuery?

I always save the result of find() to avoid multiple traversal of the tree if I need the value several times:

 var $a_bar = $('div.foo').find('a.bar'); $a_bar.removeClass(...); // ... code here $a_bar.bazz(); 

instead

 $('div.foo').find('a.bar').removeClass(...); // ... code here $('div.foo').find('a.bar').bazz(); 

I am wondering if this is not micro-optimization ... So, what is the cost / complexity of finding node in JQuery ?

+4
source share
4 answers

You can check it on js perf: http://jsperf.com/ Just create a test and run it.

I created a little test here: http://jsperf.com/jquery-find55

In my browser (firefox 18):

  • test 1 (I save the search result) for 7,074 operations per second
  • test 2 (I do not save the search result) evaluates at 1,553 operations per second

So, yes, find is "slow", and the final good idea is to store it in a variable.

+7
source

If you are going to reuse variables several times, it is definitely a great idea to cache them as you do.

.find() passing through the jQuery object that you pass in front of it, so it only looks at what is already set, which makes it very fast.

 var $mainElement = $('#whatever'), $innerLIs = $mainElement.find('li'), $innerTDs = $mainElement.find('td'); // Now that these are cached in memory, doing anything to them is very quick $innerLIs.hide(); // etc etc 

If we continue to request them, it will have to look at the DOM every time. And once this is completed, it will also wrap it in a jQuery object.

+1
source

If you are manipulating the same thing several times, it is best to make a variable.

This way you simply manipulate, and do not look at first every time.

I cut my expression a bit about code reduction a bit - here's a net-tuts article on jQuery selectors and right-to-left thinking

0
source

Choosing jQuery is known to be expensive, and then .find works. Object caching is certainly a good idea, as well as stylistically beneficial in terms of DRY.

0
source

All Articles