2012-12-13 20 views
11

Czy są one równoważne pod względem prędkości?jQuery łańcuchowa wydajność

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

lub

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

Nawet jeśli druga jest szybsza lepiej jest napisać go oddzielić aby kod był bardziej czytelny?

Odpowiedz

26

Nie, nie są one równoważne pod względem prędkości.

$(this) tworzy nowy obiekt jQuery za każdym razem. W zależności od tego, co jest this, może to być skomplikowana operacja.

Druga forma jest szybsza.

Zauważ, że dla czytelności można napisać go jako

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

Jeśli nie możesz łańcuch operacje bo masz inne linie kodu pomiędzy, można także buforować obiekt. Jest to zwykle:

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

I uwaga, że ​​attr może wziąć mapę jako argument:

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

A także łatwiejsze do odczytania po prawidłowym sformatowaniu IMO –

+3

To pełne wyjaśnienie! –

5

Dla celów czytelności można podzielić linię

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

Znam ten powinien były komentarzem, ale odstępy nie miałyby sensu.