views:

44

answers:

2

My project requires that I update the contents of a specific column in an HTML table via an AJAX call to a PHP script.

In terms of workload: The table contains about 4 columns and about 20 rows (more rows could be added with time).

What would be more (or most) efficient:

  1. Replace ONLY the column/specific cells that need to be updated
  2. Replace the entire table with the updated data

For some context: The table basically contains the name of servers in one column and their respective online status in the adjacent column. The user clicks a button to check the status of all the servers, subsequently jQuery would be called upon to update the Online Status column after the query has completed.

+2  A: 

Replacing the rows and cells that need to be will likely be faster. Though, at about 20 rows, you won't even notice a difference.

zneak
+1, and not just likely, but replacing only cells is certainly faster, simply because replacing the entire table requires the browser to recreate the DOM structure for the whole table.
casablanca
But browsers are quite fast with innerHTML, and replacing individual cells will still require a complex DOM traversal to find the nodes to replace. It certainly varies based on the content of each cell, the number to update, and the complexity of generating the table HTML from scratch.
bcherry
A: 

The only way to get the best answer is to simply benchmark each approach. It depends a lot on how your HTML generation code performs. If it's quite fast, it might be faster to build your HTML from scratch and do an innerHTML assignment on the table's parent. But if it's slow, it might be faster to iterate through each table cell and replace the contents of each. You should just run a simple benchmark.

Also, as zneak notes, it's unlikely anything you do with 20 table rows would be noticeable.

bcherry
Understood. I didn't factor in the HTML generation code time. I was only focused on the jQuery iteration time, which I now realize is only half the picture. Thanks!
Chrys G.
Just curious, what is a good way to benchmark the javasscript run time. Does firebug do something like that, or is it just simply keeping a datetime at the start and end and printing out the difference somewhere? Thanks.
Jeff T
@Jeff: A simple "difference in time" approach like you suggested will work, but your script will need to run for at least a few tens of milliseconds for you to be able to record any elapsed time.
casablanca
Usually you'll just record a start time, iterate a few thousand times or more, and record an end time, then divide by the number of iterations.
bcherry