JQuery chains faster than single instructions?

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

Example:

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

running faster / slower than

 $('#blah_id').niftyjQueryMethod1(); $('#blah_id').niftyjQueryMethod2(); 
+6
performance javascript jquery method-chaining
source share
4 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 made only once. In Example 2, this is done twice. This means that the second call will be slower.

If you do not want to put them in a chain, you can cache the selection in a variable:

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

Assuming that the methods do not affect which elements are present in the selection (for example, parent , find or filter do), this will be approximately the same as Example 1.

+6
source share

It:

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

This is probably faster:

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

But not because of the chain. This is because there is the cost of finding a selector.

It:

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

probably does not have a noticeable speed difference from the first example.

+5
source share

The first is faster. The second selector creates a jQuery object twice. If $('#blah_id') was cached and saved as a variable var $blah = $('#blah_id') and then used in the second selector as $ blah, not $('#blah_id') , then it didnโ€™t have would be the real difference.

+1
source share

Yes, chaining is faster because the DOMElement found (via $('#blah_id') ) is the only form function passed in for the function.

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

You can even set links to previously found objects:

 var myElement = $('#blah_id'); myElement.doSomething(); 
+1
source share

All Articles