Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions do chained jQuery objects offer performance gains?

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?

like image 352
buley Avatar asked Dec 07 '10 15:12

buley


1 Answers

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");
like image 60
Andy Avatar answered Oct 06 '22 02:10

Andy