<div id="parent"></div>
const node = document.getElementById('parent');
const child = document.createElement('div')
child.textContent = 'some text'
for(var i = 0; i < 5000; i++) node.appendChild(child);
const node = document.getElementById('parent');
node.innerHTML = '';
const node = document.getElementById('parent');
node.replaceChildren();
const node = document.getElementById('parent');
while(node.firstChild) node.firstChild.remove()
const node = document.getElementById('parent');
while(node.firstChild) node.removeChild(node.firstChild)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
replaceChildren | |
remove | |
removeChild |
Test name | Executions per second |
---|---|
innerHTML | 12538710.0 Ops/sec |
replaceChildren | 5380451.0 Ops/sec |
remove | 36181492.0 Ops/sec |
removeChild | 39214284.0 Ops/sec |
The benchmark analysis presented here evaluates the performance of different methods for clearing child nodes from an HTML element in JavaScript. Specifically, the performance of four different approaches is compared: innerHTML
, replaceChildren
, remove
, and removeChild
.
innerHTML:
node.innerHTML = '';
replaceChildren:
node.replaceChildren();
innerHTML
because it operates directly on the children.remove:
while(node.firstChild) node.firstChild.remove();
removeChild:
while(node.firstChild) node.removeChild(node.firstChild);
remove
, but specifically calling the removeChild
method of the parent node to explicitly remove each child.remove
, this approach suffers from the same performance concerns due to multiple DOM manipulations.From the benchmark results, we observe:
Browser Compatibility: While innerHTML
and traditional methods like removeChild
are widely supported across all browsers, replaceChildren
may not be available in very old browsers. It's essential to consider the target user base and required features of the application when choosing a method.
Readability vs. Performance: Some methods may provide better readability and maintainability of the code (for instance, remove
and removeChild
), while others might be optimized for speed (like innerHTML
for smaller DOM changes).
Potential for Memory Leaks: Using innerHTML
indiscriminately can introduce memory leaks if not handled properly (for example, if there are event listeners attached to nodes that are removed).
Other alternatives that were not benchmarked but could be considered include:
DocumentFragment
, appending children to it, and then appending it to the DOM can minimize reflows and improve performance during updates.setTimeout
can mitigate performance hits from layout thrashing caused by extensive DOM manipulations.In conclusion, the benchmark results emphasize the differences between methods used to clear child nodes in terms of performance while highlighting that performance needs to be balanced with considerations like code clarity and browser compatibility.