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();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With