Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
commandos Avatar asked Dec 13 '12 14:12

commandos


1 Answers

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
});
like image 120
Denys Séguret Avatar answered Oct 01 '22 17:10

Denys Séguret