Maksim Vi.
Maksim Vi.

Reputation: 9225

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

Upvotes: 9

Views: 1694

Answers (4)

Phrogz
Phrogz

Reputation: 303244

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.

Upvotes: 13

methodin
methodin

Reputation: 6712

The second would have to fetch ALL the items in the selector before getting the first. So the if the selector was 10,000 items it would fetch all 10,000 then the first from that group. I would hope the first would be better in this regard since it would filter as it searches (and stopping after the first was found). Probably trivial in most cases, though.

Of course if you are chaining functions then it may be unavoidable:

$('.someclass').addClass('otherClass').first().addClass('firstClass');

Upvotes: 2

xandy
xandy

Reputation: 27411

Compare $('li:first') to $('li').first(), I bet the first one must be faster. Because for example, in a document containing 100 li, then the second query would simply build a list of 100 items and then, return the first one from it; on the other hand, the first query will stop right there after the first li is returned.

Even the query is handled natively by the browser, it still takes more memory than the first one.

Upvotes: 0

shamittomar
shamittomar

Reputation: 46692

In my tests, $('mySelector:first'); is faster than $('mySelector').first();

You may also be interested in this;

Upvotes: 0

Related Questions