Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I cache $(this) in jQuery if it is used more than once?

I know that you are supposed to cache the results of a selector if you use it more than once. An example would be:

var $selected = $('.some-selected-element');

process($selected);
doStuff($selected);

But is there any performance benefit to caching $(this) if it is used multiple times?

$('.some-selector').hover(function () {
    if (!$(this).hasClass('some-other-class')) {
        $(this).addClass('another-class');
    }
    process($(this));
}
like image 407
Markus Avatar asked Jul 05 '11 19:07

Markus


2 Answers

Yes, there's a performance increase, because it prevents jQuery from having to interpret your selector.

Here's the interpretation of a selector, and what you'll be bypassing. https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

Essentially, this part

if ( selector.nodeType ) {
    this.context = this[0] = selector;
    this.length = 1;
    return this;
}
like image 164
Robert Avatar answered Sep 19 '22 02:09

Robert


Yes, there are performance benefits.

Caching the result of $(this) avoids multiple calls to the $() function and the creation of several different jQuery objects that all refer to the same element.

like image 38
Frédéric Hamidi Avatar answered Sep 21 '22 02:09

Frédéric Hamidi