Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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

expending on Ghommey's method

var Object = $('#Element');

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

Faster, and stores the object for later use.

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/

Storing the results from you jQuery selection to a variable is faster. This is because jQuery dosen't need to lookup the results every time you try to access them.

I put together some performance metrics: http://jsperf.com/jquery-selectors-vs-stored-variable

On Chrome 26.0.1410.63 on Mac OS X 10.8.2:
Selecting: 40,276 ops/sec
Storing the variable: 594,031,358 ops/sec

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top