...">

When should you use $ (object) and when should you use $ object?

Suppose I have an element that matches ".foo".

<div class="foo"></div>

      

I have learned from experience that performance is hitting from the calling searchers more than once, as if I were trying to change the same object multiple times.

$(".foo").doOneThing();
$(".foo").doAnotherThing();
$(".foo").doSomethingElse();
// Makes jQuery look for ".foo" three times, bad!

      

against

$foo = $(".foo");
$foo.callAllThreeOfTheThingMethodsInThePreviousBlock();
// Calls $(".foo") only once, but occupies memory with a jQuery object version of the foo div.

      

My question is, how many times did you have to use this crawler before setting aside memory to store the jQuery object instead of calling the jQuery method again?

I ask, since the day I made every crawler I called more than once into the $ object stored variable; my boss told me to use a finder instead of a stored object if I only used the finder, say two or three times. What do you undertake?

+3


source to share


2 answers


Use var $foo = $(".foo");

Using $(".foo")

multiple times jQuery will search again. It looks like jQuery doesn't cache selectors, and even if it did, it's best to be smart and not rely on someone else.



Does jQuery do any kind of "selector" caching?

+3


source


Storing the result of a query in a variable is recommended in most situations when a query is repeated. Depending on your situation, you can also perform functions in this sequence.



$(".foo").doOneThing().doAnotherThing().doAnotherThing();

      

+1


source







All Articles