<div id="container"></div>
var node = document.getElementById('container');
for(var i = 0; i < 1000; 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.lastChild) node.removeChild(node.lastChild)
var node = document.getElementById('container');
node.innerText = '';
var node = document.getElementById('container');
node.replaceChildren();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild | |
removeChild backwards | |
innerText | |
replaceChildren |
Test name | Executions per second |
---|---|
innerHTML | 8258531.0 Ops/sec |
removeChild | 9872132.0 Ops/sec |
removeChild backwards | 9865008.0 Ops/sec |
innerText | 7276891.0 Ops/sec |
replaceChildren | 7698579.0 Ops/sec |
Benchmark Explanation
The provided benchmark tests the performance of four different methods for clearing an element's content in JavaScript: innerHTML
, removeChild
, replaceChildren
, and innerText
. The test cases create 1000 HTML elements inside a container element and then measure how long it takes to clear the content using each method.
Comparison of Options
innerHTML
: Sets the inner HTML of an element to an empty string, effectively clearing its content.removeChild
: Removes the first child node from an element, then recursively calls removeChild
on the remaining nodes until there are no more children.innerHTML
for large datasets, as it avoids parsing and manipulating the HTML string.replaceChildren
: Replaces all child nodes of an element with new ones.removeChild
for large datasets, as it avoids recursive calls and can reuse existing DOM elements.innerText
: Sets the text content of an element to an empty string, effectively clearing its content.innerHTML
, but faster because it only updates the text content without parsing and manipulating the HTML string.Other Considerations
Library Usage
The test uses the document
object from the DOM (Document Object Model), which is a standard JavaScript library. The document.getElementById
, document.createElement
, and node.removeChild
methods are all part of this library.
Special JS Features/Syntax
There are no specific JavaScript features or syntax used in this benchmark. However, some older browsers might have had different implementations or behaviors for these methods, which could affect the results.
In summary, the test provides a useful comparison of four popular methods for clearing an element's content in JavaScript. The results indicate that replaceChildren
is generally the fastest method for large datasets, followed by removeChild
, and then innerHTML
.