开发者

Optimize jQuery selector with :first

开发者 https://www.devze.com 2023-01-29 16:21 出处:网络
I have had this feeling that $(\'.class:first\') runs faster than $(\'.class\'). So an开发者_开发问答ytime I know there only is one .class in the subset, I\'ve used it.

I have had this feeling that $('.class:first') runs faster than $('.class'). So an开发者_开发问答ytime I know there only is one .class in the subset, I've used it.

Does :first make the query run faster, or is it unnecessary?


It actually depends on the browser, :first isn't a CSS selector, it's a jQuery filter - so that requires some extra parsing work...where as .class by itself can be handed off to a native browser selector method (e.g. document.querySelectorAll() here).

Any of these would actually be faster:

$('.class').first()
//or...
$('.class').eq(0)
//or fastest:
$('.class').slice(0, 1)

...since they run native code then just take the first entry in that set.


If anything, parsing and then running the filter on the :first should make it slower. If you're looking for a single element, do:

$('.class', context).eq(0)

That way you can limit the scope of the search to context and just take out the single (or no) item using .eq(0).

0

精彩评论

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