简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM