Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, optimal usage question

I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

var thingy = $('#thingy');

Further down in the code, is there any difference in reusing thingy:

thingy.empty();

versus just making the jQuery again? :

$('#thingy').empty();

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial. What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements. Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object. But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods. I guess this is the crux of my question.

like image 983
JnBrymn Avatar asked May 16 '11 20:05

JnBrymn


2 Answers

It's not so bad if your selector is a single object, but what if your selector is $('.thingy')? Each time you create it again, it iterates the entire doc looking for that class, rather than using the stored selection. Not so bad, but then it creates a new DOM object for that selection. If there's 500 instances of .thingy, that can get really bogged down really quick.

ETA: as no.good.at.coding points out, every time you use a selector of any sort, the entire DOM is traversed. So yup - store it in a variable, call the variable.

like image 55
SickHippie Avatar answered Sep 29 '22 09:09

SickHippie


The answers to these SO questions indicate that it will be faster if you reuse the jQuery object :

  • Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?
  • Most efficient way to re-use jQuery-selected elements
like image 43
no.good.at.coding Avatar answered Sep 29 '22 08:09

no.good.at.coding