Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

performance - jQuery what is faster: selectors or methods?

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.

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;
                ...
        }
}

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 );
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The current accepted answer is not consistent with tests across many browsers comparing :first and :eq(0) to .first() and .eq(0).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...