Search code examples
jqueryperformancechaining

jQuery chaining performance


Are these equivalent in term of speed ?

$(this).attr("date",date);
$(this).attr("date_start",date_start);
$(this).attr("heure_start",heure_start);

or

$(this).attr("date",date).attr("date_start",date_start).attr("heure_start",heure_start);

Even if the second is faster is it better to write it separate to make the code more readable?


Solution

  • No, the two aren't equivalent in speed.

    $(this) builds a new jQuery object each time. And depending on what is this, this can be a complex operation.

    So the second form is faster.

    Note that for readibility you can write it as

    $(this)
        .attr("date",date)
        .attr("date_start",date_start)
        .attr("heure_start",heure_start);
    

    If you can't chain the operations because you have other lines of code in between, you can also cache the object. This is usual :

    var $this = $(this);
    $this.attr("date", date);
    $this.attr("date_start", date_start);
    $this.attr("heure_start", heure_start);
    

    And note also that attr can take a map as argument :

    $(this).attr({
        date: date,
        date_start: date_start,
        heure_start: heure_start
    });