javascript - 如何优化这个 jquery 循环的执行时间?

标签 javascript jquery performance execution-time

我有一个循环遍历带有类“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/

相关文章:

javascript - JavaScript 中的警报功能不起作用

javascript - 图片点击打开特定图片相册的灯箱

javascript - 如何使用 noUiSlider 调用更改函数?

javascript - 如何获取div的位置并突出显示它

bash - 为什么管道进入 cat 比不管道进入 cat 更快?

javascript - 使用逗号值作为饼图中的数据点

javascript - Materialisecss Autocomplete 上的两个 onChange 事件

javascript - Django 不断检查数据库中的新信息

r - 有没有一种方法可以在 R 中创建比标准矩阵使用更少内存的矩阵?

javascript - 回调和异步函数