JohnJohnGa
JohnJohnGa

Reputation: 15685

What is the cost of finding a node in JQuery?

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

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

instead of

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

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

Upvotes: 5

Views: 439

Answers (4)

tbwiii
tbwiii

Reputation: 506

If you are manipulating the same thing several times - it's best practice to make a variable.

That way you're just manipulating rather than looking it up first each time.

I removed my statement about shortening the code a little - here's a net-tuts article about jQuery selectors and "right to left" thinking

Upvotes: 0

Magus
Magus

Reputation: 15124

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

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

On my browser (firefox 18) :

  • test 1 (i save the find result) scores at 7,074 operations by second
  • test 2 (i don't save the find result) scores at 1,553 operations by second

So, yes, find is "slow" and it's definitively a good idea to store it in a variable.

Upvotes: 8

Xophmeister
Xophmeister

Reputation: 9221

jQuery's selection is known to be costly, and then running .find is even more so. Caching the objects is definitely a good idea and is also stylistically advantageous from a DRY point of view.

Upvotes: 0

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67131

If you are going to be re-using variables multiple times, it is definitely a great idea to cache them like you are doing.

.find() traversing within the jQuery object you pass before it, so it only looks within what is already given, making 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 kept querying for them, it would have to look through the DOM each time. And once that was finished, it would be wrapping it in a jQuery object each time as well.

Upvotes: 1

Related Questions