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