Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
Baijs Avatar asked Oct 22 '09 10:10

Baijs


People also ask

Which selector is faster in jQuery?

ID and Element selector are the fastest selectors in jQuery.

Which selector is faster in JavaScript?

Ofceauce ID is a faster selector in both CSS and JavaScript.

Can jQuery selector be a variable?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.


3 Answers

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.

like image 83
Alex Sexton Avatar answered Sep 22 '22 12:09

Alex Sexton


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

like image 21
rahul Avatar answered Sep 21 '22 12:09

rahul


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

$('#Element')
   .dothis()
   .dothat()
   .find('a')
      .dothat();
like image 21
jantimon Avatar answered Sep 22 '22 12:09

jantimon