jQuery:向选择器添加上下文比修饰选择器快得多? [英] jQuery: Adding context to a selector is much faster than refining your selector?
问题描述
$('li',$(' #bar'))append('bla');
速度是两倍:
$('#bar li')。append('bla');
这通常是真的吗?
向选择器添加上下文的速度比
快优化您的选择器
这在一般情况下是正确的。对于你的具体例子,但它不一定是真的jQuery< = 1.2.6。
直到和包括jQuery 1.2.6选择器引擎工作在自上而下(或从左到右)的方式。这意味着你的示例都会这样操作(大致):
var root = document.getElementById('bar');
return root.getElementsByTagName('li');
jQuery 1.3.x(ie, Sizzle ,jQuery嵌入其中)介绍自下而上(或从右到左)方法来查询DOM。 $('#bar li')
现在变为(大致):
var results = [];
var elements = document.getElementsByTagName('li');
for(var i = 0; i var element = elements [i];
var parent = element.parentNode;
while(parent){
if(parent.id =='bar'){
results.push(element)
break;
}
parent = parent.parentNode;
}
}
返回结果
两种方法。您发现了一个缺点。
编辑:刚刚从这个讨论,Sizzle中继现在对 #id
的选择器进行特殊豁免。它使用它作为根上下文,加快了一些东西。如果不消除您看到的速度差异,这应该减少。
I just noticed that adding context to the selector is much faster than refining your selector.
$('li',$('#bar')).append('bla');
Is twice as faster than:
$('#bar li').append('bla');
Is this generally true?
adding context to the selector is much faster than refining your selector
This is true in the general case. With respect to your specific examples however it is not necessarily true for jQuery <= 1.2.6.
Up to and including jQuery 1.2.6 the selector engine worked in a "top down" (or "left to right") manner. Meaning that both your examples would operate like this (roughly):
var root = document.getElementById('bar');
return root.getElementsByTagName('li');
jQuery 1.3.x (ie, Sizzle, which jQuery embeds) introduced a "bottom up" (or "right to left") approach to querying the DOM. So $('#bar li')
now becomes (roughly):
var results = [];
var elements = document.getElementsByTagName('li');
for(var i=0; i < elements.length; i++) {
var element = elements[i];
var parent = element.parentNode;
while(parent) {
if(parent.id == 'bar') {
results.push(element)
break;
}
parent = parent.parentNode;
}
}
return results
There are benefits and downsides to both approaches. You found one of the downsides.
Edit: just found out from this discussion that Sizzle trunk now makes a special exemption of selectors where #id
is first. It uses that as the root context, speeding things up a bit. This should diminish if not eliminate the speed differences you are seeing.
这篇关于jQuery:向选择器添加上下文比修饰选择器快得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!