我有一个循环遍历带有类“GridCell”的表格单元格中的所有 div。 要求在某些情况下会发生这种情况,即调整网格或列的大小时。
我扩展了行数和列数,以查看更多时间差异,现在循环大约为 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。是什么造成了这种差异?
附注我以什么顺序执行循环并不重要。第一个循环总是比其他循环慢很多,当该循环最后执行时也是如此。
最佳答案
// collect the widths from the first row only
var widths = $('table.Grid tbody tr:first-child td.GridCell').map(function(idx) {
return $(this).width() - 3;
// or use:
// return this.clientWidth - 3;
// if you're not targeting IE <= 7
});
// apply the widths to each div
$('table.Grid tbody td.GridCell > div').each(function(idx) {
this.style.width = widths[idx % widths.length] + 'px';
});
关于javascript - 如何优化这个 jquery 循环的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12174005/