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

那年仲夏 提交于 2020-01-09 11:13:34

问题


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

回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6587687/should-i-cache-this-in-jquery-if-it-is-used-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!