jQuery什么更快:选择器或方法? [英] jQuery what is faster: selectors or methods?

查看:117
本文介绍了jQuery什么更快:选择器或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有$('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 );
};

推荐答案

当前接受的答案与

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什么更快:选择器或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆