jQuery选择器的性能与局部变量的关系 [英] Performance of jQuery selectors vs local variables
问题描述
当需要在函数范围内多次访问jQuery选择器的结果时,是否建议我运行一次选择器并将其分配给局部变量?
Is it recommended that, when I need to access the result of a jQuery selector more than once in the scope of a function, that I run the selector once and assign it to a local variable?
在这里原谅我的陈腐例子,但我认为它说明了这个问题. 因此,此代码的执行速度会更快:
Forgive my trite example here, but i think it illustrates the question. So, will this code perform faster:
var execute = function(){
var element = $('.myElement');
element.css('color','green');
element.attr('title','My Element');
element.click(function(){
console.log('clicked');
});
}
不是此代码:
var execute = function(){
$('.myElement').css('color','green');
$('.myElement').attr('title','My Element');
$('.myElement').click(function(){
console.log('clicked');
});
}
如果没有区别,谁能解释为什么? jQuery在选择元素后是否会缓存元素,以使后续的选择器不必再次搜索dom?
If there is no difference, can anyone explain why? Does jQuery cache elements after selecting them so subsequent selectors don't have to bother searching the dom again?
推荐答案
第一种情况,重用选择器引用绝对更快.这是我做为证明的测试:
Reusing the selector reference, your first case, is definitely faster. Here's a test I made as proof:
http://jsperf.com/caching-jquery-selectors
后一种情况(重新定义选择器)的速度要慢35%.
The latter case, redefining your selectors, is reported as ~35% slower.
这篇关于jQuery选择器的性能与局部变量的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!