问题描述
假设我有$('mySelector:first');
和$('mySelector').first();
.哪种方法最有效?我查看了源代码,但仍然无法弄清楚.
Let's say I have $('mySelector:first');
and $('mySelector').first();
. Which way is the most efficient? I looked in the source, but still couldn't figure it out.
在第一种情况下,jQuery会遍历每个项目,直到获得第一个:
It looks like in the first case jQuery goes through every item until gets the first one:
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
...
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
...
}
}
在第二种情况下,jQuery对集合进行了切片,但是我不确定它的效率如何:
In second case jQuery slices the collection, but I am not sure how efficient it is:
function first() {
return this.eq( 0 );
};
function eq( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
};
推荐答案
当前接受的答案与,将:first
和:eq(0)
与.first()
和.eq(0)
进行比较.
The current accepted answer is not consistent with tests across many browsers comparing :first
and :eq(0)
to .first()
and .eq(0)
.
对于当前的主要桌面浏览器:
$('foo').first()
几乎是$('foo:first')
For the current major desktop browsers:$('foo').first()
is almost four times faster than $('foo:first')
如果要检查方法,请此处是测试及其当前结果.
If you want to inspect the methodology, here are the tests and their current results.
这篇关于jQuery什么更快:选择器或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!