多次使用jQuery $()运算符会对性能产生影响吗? [英] Is there a performance impact to using the jQuery $() operator many times?

查看:93
本文介绍了多次使用jQuery $()运算符会对性能产生影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在元素周围或多次构造一个jQuery对象,是否存在显着差异?例如:

Is there a significant difference if I construct a jQuery object around an element once or many times? For instance:

var jEl = $(el);
$.each(myArray, function() {
    jEl.addClass(this);
}

与:

$.each(myArray, function() {
    $(el).addClass(this);
}

我知道还有其他方法可以写下这可能会回避这个问题,但我的问题是我是否应该只做一次$(el),或者它是否真的无关紧要。这个例子是做作的。

I know there are other ways to write this that might sidestep the issue, but my question is about whether I should work to do $(el) just once, or if it truly is irrelevant. The example is contrived.

奖励点用于解释$(el)在幕后的作用。

Bonus points for explaining just what $(el) does behind the scenes.

我知道理论上我正在做更多的工作,我不知道的是是否重要...如果jQuery缓存它或浏览器都非常擅长第二个请求或其他什么,而不是它的价值。

I know that theoretically more work is being done, what I don't know is whether it matters... if jQuery caches it or the browsers are all really good at the second request or whatever, than its not worth it.

FYI:相关的jQuery API链接在这里(我提供的是因为$()对Google来说不是最简单的事情): http://api.jquery.com/jQuery/#using-dom-元素

FYI: The relevant jQuery API link is here (which I provide because $() isn't the easiest thing to Google for): http://api.jquery.com/jQuery/#using-dom-elements

还值得包括这个有用的链接: http://www.artzstudio.com/2009/04/jquery-performance-rules/ ,他的几个要点围绕着保存,链接和选择。

Also worth including this useful link: http://www.artzstudio.com/2009/04/jquery-performance-rules/, where several of his points center around saving, chaining, and selecting well.

推荐答案

是的,会对性能产生影响。

Yes, there is a performance impact.

在第一个例如,只创建了一个实例。

In the first example, only one instance is created.

在第二个实例中,将为循环的每次迭代创建一个实例。

In the second, an instance will be created for each iteration of the loop.

根据 myArray 的大小,这可能导致创建大量无关实例,这些实例将通过内存进行咀嚼。

Depending on the size of myArray, that could lead to a lot of extraneous instances being created which will chew through memory.

这篇关于多次使用jQuery $()运算符会对性能产生影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆