我增加了行和列的数量,以便更容易看到时间差异,目前循环大约需要750毫秒。
但是我不理解的是,'循环的一部分'要快得多。请参见以下三个循环。第一个循环很慢。只执行第一个循环的一部分的第二个和第三个循环非常快速。
//Around 750 ms
$('table.Grid tbody td.GridCell > div').each(function() {
var width = $(this).parent().width();
$(this).css('width', width - 3);
});
//Around 60 ms
$('table.Grid tbody td.GridCell > div').each(function() {
var width = $(this).parent().width();
});
//Around 15 ms
$('table.Grid tbody td.GridCell > div').each(function() {
$(this).css('width', 100);
});
一条指令只需要60或15毫秒,但两个指令一起需要750毫秒。是什么造成了这种差异呢?
附注:执行循环的顺序无关紧要。第一个循环总是比其他循环慢得多,即使它是在最后执行的。
$(this)
,那么如果你创建一个对它的单一引用,会怎样呢? - Fabrizio Calderan.GridCell
类吗? - Alnitak