Under what conditions do chained jQuery objects offer performance gains?

javascript, jquery

Solution

Would a chained objects do their work any faster than two non-chained ones? If so, why?

Chained objects are faster when they start with a selector, and chaining prevents the selector being run against the DOM multiple times (a comparatively expensive operation).

Slower:

$(".myClass").val(123);
$(".myClass").addClass("newClass");

Faster:

$(".myClass")
    .val(123)
    .addClass("newClass");

Caching the selector in a variable has the same benefits as chaining (i.e. preventing expensive DOM lookups):

var $selctor = $(".myClass");
$selector.val(123);
$selector.addClass("newClass");

Problem

I'm working with some code that adds and removes various CSS classes on the same object. The code looks something like: ``` function switch_states(object_to_change) { if(object_to_change.hasClass('ready') { object_to_change.removeClass('ready'); object_to_change.addClass('not_ready'); } else { object_to_change.removeClass('not_ready'); object_to_change.addClass('ready'); } } ``` I suspect I might be able get away with chaining these two snippits into something like `object_to_change.removeClass('ready').addClass('not_ready');` But I have to wonder: besides legibility and the neato factor, does this give me any performance gains? My question: Would a chained objects do their work any faster than two non-chained ones? If so, why? If not, at what point does using chained objects become more efficient than disparate ones -- i.e. under what conditions do chained jQuery objects offer performance gains?

Original source