views:

208

answers:

2

This method is used to hide columns in a table based on a collection of metadata json objects. There is an object per column in the table. Currently on a table that has ~500 rows and ~15 columns with 6 being hidden this method takes ~2 seconds to execute.

I am attempting to optimize it to be faster. Any suggestions?

function hideHiddenColumns() {
  if (tableMetaData.length) {
    for (var index = 0; index < tableMetaData.length; index++) {
      var item = tableMetaData[index];
      if (!item.DisplayFlag) {
        $table.find('th:nth-child(' + (index + 1) + '), td:nth-child(' + (index + 1) + ')').hide();
      }
    }
  }
}
+2  A: 

I'm not sure where $table comes from, but how about good old DOM instead of a complex jQuery selector:

$table.each( function() {
  var rows = this.rows;
  var rowCount = rows.length;

  for (var i = 0; i < rowCount; i++) {
    var cells = rows[i].cells;
    if (cells.length > index) {
      $(cells[index]).hide();
    }
  }
});

Obviously this implies that no merged cells exist in the table.

Tomalak
+2  A: 

Go with plain JS, jsust as Tomalak suggested. You can also optimize the for loop with while:

var item, i = tableMetaData.length;
while (i--) {
  item = tableMetaData[i];
  // do what's gotta be done
}

The reversed while loop used to be by far the fastest looping structure. With the recent improvements in latest JS engines the difference is not that big anymore though

Damir Zekić