jquery - fastest way to remove all rows from a very large table
I thought this might be a fast way to remove the contents of a very large table (3000 rows):
$jq("tbody", myTable).remove();
But it's taking around five seconds to complete in firefox. Am I doing something dumb (aside from trying to load 3000 rows in to a browser)? Is there faster way to do it?
$("#your-table-id").empty();
That's as fast as you get.
It's better to avoid any kind of loops, just remove all elements directly like this:
$("#mytable > tbody").html("");
$("#myTable > tbody").empty();
It won't touch the headers.
Using detach is magnitudes faster than any of the other answers here:
$('#mytable').find('tbody').detach();
Don't forget to put the tbody element back into the table since detach removed it:
$('#mytable').append($('<tbody>'));
Also note that when talking efficiency $(target).find(child)
syntax is faster than $(target > child)
. Why? Sizzle!
Elapsed Time to Empty 3,161 Table Rows
Using the Detach() method (as shown in my example above):
- Firefox: 0.027s
- Chrome: 0.027s
- Edge: 1.73s
- IE11: 4.02s
Using the empty() method:
- Firefox: 0.055s
- Chrome: 0.052s
- Edge: 137.99s (might as well be frozen)
- IE11: Freezes and never returns
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.