<div id="parent"></div>
const node = document.getElementById('parent');
const child = document.createElement('div')
child.classList.add('child')
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)
const node = document.querySelectorAll('.child');
for (const child of node) child.remove()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
replaceChildren | |
remove by while | |
removeChild by while | |
remove by forEach |
Test name | Executions per second |
---|---|
innerHTML | 2393813.8 Ops/sec |
replaceChildren | 1947323.5 Ops/sec |
remove by while | 22930084.0 Ops/sec |
removeChild by while | 19834692.0 Ops/sec |
remove by forEach | 1232102.6 Ops/sec |
The benchmark provided evaluates different methods of manipulating the DOM (Document Object Model) by removing child elements from a parent node. In this test, the focus is on measuring the performance of various DOM manipulation techniques using JavaScript.
innerHTML:
node.innerHTML = '';
replaceChildren:
node.replaceChildren();
remove by while (with remove):
while(node.firstChild) node.firstChild.remove();
removeChild by while:
while(node.firstChild) node.removeChild(node.firstChild);
removeChild
.remove
.remove by forEach:
const node = document.querySelectorAll('.child'); for (const child of node) child.remove();
replaceChildren
are newer methods and may not be supported in older browsers; therefore, developers must consider what browsers their applications aim to support.innerHTML
are easier to read, they may come with performance costs that grow in significance in applications with extensive DOM manipulation.Outside the methods tested, other alternatives for DOM manipulation include:
DocumentFragment
to minimize reflows while assembling a set of nodes before inserting them into the DOM can provide improved performance for bulk operations.In conclusion, the benchmark comprehensively tests various methods for manipulating the DOM, illuminating strengths and weaknesses that will help developers make informed decisions based on their project requirements.