2012-12-13 43 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

不,这两者在速度上并不相同。

$(this)每次都会建立一个新的jQuery对象。根据什么是this,这可能是一个复杂的操作。

所以第二种形式更快。

注意,为了可读性,你可以把它写成

$(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); 

我知道这应该已经是一个评论,但间隔将是没有意义的。