<div id="container"></div>
var node = document.getElementById('container');
for(var i = 0; i < 100; i++) node.appendChild(document.createElement('div'));
var node = document.getElementById('container');
node.innerHTML = '';
var node = document.getElementById('container');
while(node.firstChild) node.removeChild(node.firstChild)
var node = document.getElementById('container');
while(node.firstChild) node.firstChild.remove()
var node = document.getElementById('container');
node.innerText = '';
var node = document.getElementById('container');
node.textContent = '';
var node = document.getElementById('container');
node.replaceChildren()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild | |
remove | |
innerText | |
textContent | |
replaceChildren |
Test name | Executions per second |
---|---|
innerHTML | 2836759.8 Ops/sec |
removeChild | 4971886.0 Ops/sec |
remove | 4976255.5 Ops/sec |
innerText | 3639106.5 Ops/sec |
textContent | 2721220.0 Ops/sec |
replaceChildren | 2762901.0 Ops/sec |
The benchmark defined in the provided JSON compares different methods of manipulating the DOM (Document Object Model) in JavaScript, specifically for clearing out child elements from a container nodes.
innerHTML:
node.innerHTML = '';
removeChild:
while(node.firstChild) node.removeChild(node.firstChild);
remove:
while(node.firstChild) node.firstChild.remove();
remove()
method on each first child in a loop until the node is empty.removeChild
, but potentially cleaner to read, and remove()
directly acts on the nodes.innerText:
node.innerText = '';
innerHTML
, but it specifically manipulates text content.innerHTML
.textContent:
node.textContent = '';
innerHTML
and more secure as it does not parse HTML.innerText
, it may not behave well with styled or hidden elements.replaceChildren:
node.replaceChildren();
From the benchmark results:
remove
, achieving around 4.98 million executions per second.removeChild
was also quite fast, just slightly slower.innerText
and innerHTML
performed significantly slower, while textContent
and replaceChildren
were the slowest in this particular benchmark.replaceChildren
is not supported in older versions of Internet Explorer.innerHTML
can introduce security risks (e.g., XSS attacks) if any user-generated content is involved.DocumentFragment
) to minimize layout recalculations.This benchmark demonstrates the performance differences in how various common DOM manipulation methods operate, allowing developers to choose the most suitable technique based on their specific use case.