2012-12-13 12 views
11

Sono equivalenti in termini di velocità?jQuery chaining performance

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

o

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

Anche se il secondo è più veloce è meglio scriverlo separare per rendere il codice più leggibile?

risposta

26

No, i due non sono equivalenti in termini di velocità.

$(this) crea ogni volta un nuovo oggetto jQuery. E a seconda di cosa sia this, questa può essere un'operazione complessa.

Quindi il secondo modulo è più veloce.

Si noti che per leggibilità si può scrivere come

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

Se non è possibile a catena le operazioni perché avete altre righe di codice in mezzo, è anche possibile memorizzare nella cache l'oggetto. Questo è normale:

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

E nota anche che attr può prendere una mappa come argomento:

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

E anche più facile da leggere se formattato correttamente IMO –

+3

Questa è una spiegazione completa! –

5

Per scopi di leggibilità si potrebbe dividere la linea di

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

so che questo dovrebbe è stato un commento ma la spaziatura non avrebbe avuto senso.