JQuery, optimal use issue

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

var thingy = $('#thingy'); 

Further in the code, is there a difference in reusing thingy :

 thingy.empty(); 

instead of creating jQuery again?

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

I assume that in the second case we need to create another jQuery object, but I suspect this is trivial. What I'm trying to avoid by simply reusing a variable is doing a DOM search to match elements. Perhaps this search happens anyway?

My initial assumption was that the document is scanned when the $ object is created. But then it occurred to me that the $ object might just be an iterator that views the document again every time you execute one of its methods. I think this is the essence of my question.

+6
source share
4 answers

It's not so bad if your selector is the only object, but what if your selector is $ ('. Thingy')? Each time you create it again, iterates through the entire document looking for this class, instead of using the stored selection. Not so bad, but then it creates a new DOM object for this choice. If there are 500 copies of .thigh that can really get stuck very quickly.

ETA: as stated in good.at.coding, every time you use a selector, the whole DOM goes through. So yup - save it in a variable, call the variable.

+5
source

Another thing to consider is DOM changes. Make sure nothing happens after you install the thing, which causes $ ('# thingy') to go away!

+2
source

Generally speaking, you will want to "cache" the results of the selector if you are sure that they will not change.

Your example is pretty trivial, as the #id selector is already quite efficient (in fact, it just passes it directly to the document.getElementById() call.

As already mentioned, you start to see savings when you use less efficient selectors (for example, $('.class') ).

Using variables in this way can save you a lot of extra processing. eg:

 var tree = $('.bigTree'); // Do random stuff with tree // ... var segment = tree.find('.subsection'); // Do random stuff with segment... 

In the above example, the segment variable can use the results of the variable tree without having to re-access the entire DOM, preserving this performance bit. While trivial examples like this are rarely worth it, to be sure that you are doing such things for bits of code (e.g. loops) can greatly speed up your application.

Of course, make sure that if you dynamically update the DOM, you use a "fresh" selector to make sure you select any changes :)

+1
source

Source: https://habr.com/ru/post/888259/


All Articles