Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 724
maximus Avatar asked Apr 03 '11 20:04

maximus


2 Answers

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.

like image 162
lonesomeday Avatar answered Oct 01 '22 22:10

lonesomeday


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.

like image 32
Weston C Avatar answered Oct 01 '22 22:10

Weston C