Search code examples
javascriptjqueryperformanceexecution-time

How can I optimize execution time of this jquery loop?


I have a loop thats going through all div's in a table cel with class 'GridCell'. It is required that this happens in some situations, when the grid or columns are resized.

I extended the number of rows and columns, to see more time differences, and the loop is around 750 ms right now.

But what I don't understand, is that 'just a part of the loop' is a lot faster. See the following three loops. The first is slow. The second and third loop that only do a part of the first loop are really fast.

//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);
});

So one line, is only 60 or 15 ms, but the two together are 750. What makes this difference?

p.s. It doesn't matter in what sequence I execute the loops. The first loop is always a lot slower then the others, also when that loop is executed last.


Solution

  • // 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';
    });