-1
  • Are there any other optimization techniques or best practices I can apply to improve the performance of this script?

Code snippet:

// Simplified example
$('#table-body').empty();
data.forEach(function(row) {
  $('#table-body').append('<tr>...</tr>');
});
  • I'm using jQuery 3.6 to dynamically update a table with thousands of rows based on user input.
  • The script uses .append() and .remove() methods to update the table contents.
  • However, with large datasets, the script takes several seconds to execute, causing a noticeable delay.
  • I've tried using .detach() and .empty() instead, but the performance improvement is minimal.
2
  • Can you make the slowdown reproducible? It would be good to have a runnable snippet that initialises data with fake data (like just a sequence of numbers or whatever), and then populates a table. If it is relevant to do .remove() calls to reproduce the problem, then add those, otherwise remove the mention of it in your question.
    – trincot
    Commented Sep 5, 2024 at 8:35
  • The slowest operation you can do is to manipulate the DOM. The slowest DOM manipulation is to change table as it requires the entire table layout to be recalculated based on the updated text. You do both of these every iteration. Batch the changes and determine batch size to balance UI updates with UI update speed and browser memory usage (ie don't try to build a string of 1mill rows in one go).
    – fdomn-m
    Commented Sep 5, 2024 at 10:19

1 Answer 1

2

Each append will modify the DOM, which is inefficient

Try this - I assume the data can be trusted and has been sanitized

$('#table-body').html(
  data.map((row) => `<tr><td>${row.somevalue}</td></tr>`).join('')
);

In plain JS

document.getElementById('table-body').innerHTML = data
  .map((row) => `<tr><td>${row.somevalue}</td></tr>`).join('');

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.