简体   繁体   中英

Is there a performance difference between jquery selector or a variable

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.

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.

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.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM