tag - jquery this




jQuery chaining performance (2)

For readability purposes you could split the line to

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

I know this should have been a comment but the spacing would have made no sense as one.

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?


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
});




chaining