开发者

Pseudo-selectors vs methods

Just interested, which one's faster? Couldn't google it up.

For example, $('li:first') vs开发者_StackOverflow $('li').first()


Update: apparently the parsing of the expression incurs a lot of overhead. In my quick benchmark .first() is a lot faster than using the selector.

Expressions simply boil down to methods on the $.expr object like explained here

The actual implementation of the :first vs the .first() differ a bit:

Here the code for :first on $.expr.setFilters.first

function ( elem, i ) {
  return i === 0;
}

while $.fn.first is simply a shorthand for .eq(0):

function () {
  return this.eq( 0 );
}

without looking at the actual code I'd implement a first() like this if it wasn't there:

$.extend($.expr[':'],{
    first: function(a) {
        return $(a).first();
    }
});

This also means that :first is simply a filter on a list of elements, while .first() is a reduce operation that's more efficient.

Update2: Doh - Should have read the docs. Since jQuery tries to use native CSS selectors in modern browsers and :first is no selector from the CSS spec it will always perform a lot worse than a real selector that can take advantage of the browsers native CSS searching methods (whereas jQuery has to emulate that behavior in JS)


$('li').first() is about ten times faster than using $('li:first'). Tested using Firefox 3.6.

100,000 iterations:
55,870ms using :first
5,858ms using .first()

using this code :

$(document).ready (function() {
var i, time = +new Date;
for ( i = 0; i < 100000; ++i ) {
$('li:first');
}
console.log ( (+new Date) - time );
time = +new Date;
for ( i = 0; i < 100000; ++i ) {
$ $('li').first();
}
console.log ( (+new Date) - time );
});


I'm not completely sure but my guess would be that internally it would work the same, so the performance would not differ that much. But I can be completely wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜