Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are long jQuery chains bad?

I've been using jQuery a long time and I've been writing a slideshow plugin for my work and I (not 100% consciously) wrote probably 75% it in a single chain. It's fully commented and i specify each end() and what it's resetting it to, etc, but does this slow down jQuery or the DOM loading, or, does this actually speed it up?

like image 203
Oscar Godson Avatar asked Dec 15 '10 18:12

Oscar Godson


4 Answers

It depends on your specific code, as always. As for storing a reference vs .end(), well...with a really long chain, it's faster not to chain vs .end() calls, simply because you have to handle the extra baggage (storing/restoring), like the .prevObject reference, the .selector, .context, etc that you probably don't care about in many cases....and just more intertwined references to previous objects.

Where it's more costly is harder to measure...it's not the execution (though that is slower, even if infinitesimally)...it's the more complicated garbage collection to clean up all those objects later, since the dependency graph is now much larger.

Now...will it make a measurable difference? not unless your chain is really long, in which case it's probably a micro-optimization you need not worry about in most cases.

99% of the time, unless you're making some egregious performance penalizing call, don't worry about it, as with most micro-optimizations. If you're having a problem with performance, then get into it.

like image 139
Nick Craver Avatar answered Nov 04 '22 00:11

Nick Craver


One of the most expensive things you can do in a modern browser is to access and manipulate the DOM. Chaining lets you minimize the actual lookups that you have to do, which can mean significantly faster code. The other option is to do the initial lookup, store that in a variable, and do everything off of that variable. That being said, jquery was specifically designed with that chaining api in mind, so it is more idiomatic to chain.

like image 6
Matt Briggs Avatar answered Nov 03 '22 23:11

Matt Briggs


I think chainability of jQuery is a great feature ... one should really use it more often. for example:

$(this)
  .find('.funky')
  .css('width', 30)
  .attr('title', 'Funky Title')
.end()
.fadeIn();

is much better (and elegant) - don't have to create 2 jQuery $(this) objects than :

$(this).find('.funky').css('width', 30).attr('title', 'Funky Title');
$(this).fadeIn();
like image 4
kares Avatar answered Nov 04 '22 01:11

kares


My guess would be no difference, or faster, due to lack of intermediaries.

The only major drawback is to clarity, if you think via comments that it is obvious without making it multi-line with intermediate variables, via virtue of comments or just a nicely clean call chain then fine.

like image 2
Orbling Avatar answered Nov 04 '22 00:11

Orbling