maximus
maximus

Reputation: 2437

jQuery chaining faster than separate statements?

Is it faster to write separate calls to the jQuery function, or to use a single chain? If an added explanation of why one is faster than the other, it will be greatly appreciated :-)

An example:

$('#blah_id').niftyjQueryMethod1().niftyjQueryMethod2();

is faster/slower than

$('#blah_id').niftyjQueryMethod1();
$('#blah_id').niftyjQueryMethod2();

Upvotes: 6

Views: 1422

Answers (4)

buschtoens
buschtoens

Reputation: 8551

Yeah, chaining is faster, because the found DOMElement (via the $('#blah_id')) is only directly passed form function to function.

If you seperate them, the DOMElement has to be found again and again and again. Every $("selector") is evil. Try to avoid them as often as possible.

You can even set references to the previosuly found objets:

var myElement = $('#blah_id');

myElement.doSomething();

Upvotes: 1

Weston C
Weston C

Reputation: 3642

This:

$('#blah_id').niftyjQueryMethod1().niftyjQueryMethod2();

Probably is faster than this:

$('#blah_id').niftyjQueryMethod1(); $('#blah_id').niftyjQueryMethod2();

But not because of the chaining. It's because there's a cost to the selector lookup.

This:

var $blah = $('#blah_id');
$blah.niftyjQueryMethod1();
$blah.niftyjQueryMethod2();

probably has no appreciable difference in speed from the first example.

Upvotes: 6

lonesomeday
lonesomeday

Reputation: 238115

In your example, chaining is faster.

// Example 1
$('#blah_id').niftyjQueryMethod1().niftyjQueryMethod2();

// Example 2
$('#blah_id').niftyjQueryMethod1();
$('#blah_id').niftyjQueryMethod2();

In example 1, the call to create the jQuery object ($('#blah_id')) is only made once. In example 2, it is made twice. This means the second call will be slower.

If you don't want to put them all in a chain, you can cache the selection in a variable:

var blah = $('#blah_id');
blah.niftyjQueryMethod1();
blah.niftyjQueryMethod2();

Presuming that the methods don't affect what elements are present in the selection selection (like, for example, parent, find, or filter do) this will be pretty much exactly the same as example 1.

Upvotes: 7

Hussein
Hussein

Reputation: 42818

First one is faster. In the second selector is creating a jQuery object twice. If $('#blah_id') was cached and stored as a variable var $blah = $('#blah_id') and then using in your second selector as $blah and not $('#blah_id') then it would make no real difference.

Upvotes: 1

Related Questions