2012-12-13 3 views
11

これらのスピードは同等ですか?jQueryチェーニングのパフォーマンス

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

または

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

秒は速い場合であっても、それは良いコードを読みやすくするために別のことを書くことですか?

答えて

26

いいえ、2つは同等の速度ではありません。

$(this)は、毎回新しいjQueryオブジェクトを作成します。 thisに応じて、これは複雑な操作になります。

したがって、2番目のフォームは高速です。 readibilityのためにあなたが間のコードの他の行を持っているので、あなたが操作をチェーンできない場合、あなたはまた、オブジェクトをキャッシュすることができ

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

としてそれを書くことができることを

は注意してください。これは普通です:

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

そしてノートもそれattrは、引数としてマップを取ることができます:読みやすさの目的のために

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

また、正しくフォーマットされたときに読みやすくIMO –

+3

それは完全な説明です! –

5

あなたは

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

に行を分割することができ、私はこれがすべき知っていますコメントされていますが、スペーシングは意味をなさないでしょう。

関連する問題