views:

180

answers:

5

Lately i have been wondering if there is a performance difference between repeating the selector just over and over again or just using a var and store the selector in that and just refer to it.

$('#Element').dothis();

$('#Element').dothat();

$('#Element').find('a').dothat();

or just

var Object = $('#Element');

Object.dothis();

Object.dothat();

$('a', Object).dothat();

I prefer the second way because it looks cleaner and is better maintainable.

+2  A: 

I prefer the second way. It will be easier to maintain code even if an element id or class changes.

rahul
+1 for "easier to maintain code"
smack0007
+4  A: 

There is certainly a performance difference, since sizzle does not have to be executed each time, however, there is also a functionality difference. If the dom happens to change between the 1st and 3rd calls, the cached jQuery object will still contain the old set of elements. This can often occur if you cache a set and then use it in a callback.

Alex Sexton
Any idea on how to get around that? That is, to store the selector in a variable but have it account for a changing DOM? All I can think of is storing a function that returns the selector in the variable (but it doesn't seem to work for me)
Konrad
Invalidating a selection can be really tough, and no one does it because of old browsers and race conditions. The best way to do it, if you are writing all the code that changes your dom, add the elements to the collections yourself whenever you make a change. So if you insert something you know you have a collection for, do a `$mycollection.add(newNode);`
Alex Sexton
+2  A: 

There is another fast way. It is as fast as your second code.

$('#Element')
   .dothis()
   .dothat()
   .find('a')
      .dothat();
Ghommey
+1  A: 

The second way has a performance benefit. It may or may not be great but it is better. In the first version, you're doing dom traversal 4 times, in the second you only do 2.

Pretty good article on speeding up jQuery here: http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

smack0007
+1  A: 

expending on Ghommey's method

var Object = $('#Element');

Object
   .dothis()
   .dothat()
   .find('a')
      .dothat();

Faster, and stores the object for later use.

dotty