Markus
Markus

Reputation: 63

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));
}

Upvotes: 6

Views: 1168

Answers (4)

Berry Phillips
Berry Phillips

Reputation: 51

jsperf.com is a great resource - and one I've taken to frequenting of late - for evaluating JavaScript performance. For example, the following test evaluates the performance of cached jQuery elements to that of non-cached:

http://jsperf.com/jquery-cache-vs-no-cache

The results echo the answers in this thread.

Upvotes: 0

Robert
Robert

Reputation: 21388

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;
}

Upvotes: 8

matsko
matsko

Reputation: 22183

The $() function finds the DOM node for the element and applies the prototyped methods to it for browsers that don't already add them when defined (IE browsers). So constantly calling it will perform this operation. It is better for performance and readability to cache the output of the $() function call to a variable.

Upvotes: 0

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

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.

Upvotes: 3

Related Questions