3

I have a function that is called on document.ready that loops through a table with roughly 600 rows that was generated in classic ASP. In a "modern" browser (Chrome, Firefox, IE9 Beta) it runs in under 1.5-2 seconds. In IE6 it runs in around 5-7 seconds, not good.

Basically what I'm doing is adding the value of the cells in certain columns and giving subtotals. (I know, this should be generated on the server-side, but some brainiac developed this using views that calls views, who call views, who call views...).

I used IE9's profiler to try to get a sense of where a bottle neck is and it seems to be most profound when jQuery's find and each is called:

tr.find("td").each(function() {
&
tr.find("td").eq(ci).html(tot).css

I will post all of the code if necessary but I was wondering is there a more efficient way of looping through unnamed table rows and cells?

The table looks like:

32     47       0/0 0 8 1 1                 
32     47  -7   0/0 0 0   7 
Totals     -7   0/0   8 1 8  
32     47       0/0 0 2 1 1                 
32     47  -7   0/0 0 3   7 
Totals     -7   0/0   5 1 8  

I loop through the table rows and if I find a (td:first) = "Totals" then I place the current tr, and the two previous tr's in variables, then grab cells and calculate totals, and place those totals in the appropriate cells.

This all works but like I said there is a serious bottle neck during find and each.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
wali
  • 477
  • 7
  • 19

1 Answers1

4

I haven't tested it myself, but it's possible that all the jQuery extensions are what's slowing things down. Try doing this with plain javascript and see if it speeds things up:

var rows = document.getElementById('your-table').rows;
var num_rows = rows.length;
for (var i = 0; i < num_rows; ++i) {
    var cells = rows[i].cells;
    if (cells[0].innerHTML == 'Totals') {
       var num_cells = cells.length;
       for (var j = 1; j < num_cells; ++j) {
           cells[j].innerHTML =
               (parseInt(rows[i-2].cells[j]) || 0) +
               (parseInt(rows[i-1].cells[j]) || 0);
       }
    }
 }
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • I'll try it this evening/in the morning and report my findings...Thanks! – wali Nov 18 '10 at 21:58
  • 1
    +1 - The `rows` and `cells` properties are a great way to speed up table iteration. Only thing I might add would be to cache the current row and the current cell in each `for` loop. Those property lookups add up. – user113716 Nov 18 '10 at 21:59
  • ...actually, I guess it would be just the row. Not the cell. – user113716 Nov 18 '10 at 22:06
  • 1
    @patrick, I cached the "table.rows[i].cells" which makes sense. You could even go further and cache the previous two rows (so when it comes time to add, you can just reference the cached rows). Or if you know the table is structured in sets of 3, you could start the outer for loop at `i = 2` and just do `i += 3` instead of `++i`. – Ben Lee Nov 18 '10 at 22:12