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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With