<div id="container1"></div>
<div id="container2"></div>
const container1 = document.querySelector('#container1');
const container2 = document.querySelector('#container2');
for (let i=0; i<300; i++) {
container1.appendChild(document.createElement('p'));
container2.appendChild(document.createElement('p'));
}
container1.replaceChildren(container2.children);
while (container1.firstChild)
container1.removeChild(container1.firstChild);
while (container2.firstChild)
container1.appendChild(container2.firstChild);
while (container1.firstChild)
container1.removeChild(container1.firstChild);
container1.replaceChildren(container2.children);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
replaceChildren | |
remove and insert | |
remove and replace |
Test name | Executions per second |
---|---|
replaceChildren | 480284.0 Ops/sec |
remove and insert | 681723.9 Ops/sec |
remove and replace | 362125.1 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmarking test, where users can compare the performance of different approaches to clear element content on HTML elements. The benchmark consists of three individual test cases: "replaceChildren", "remove and insert", and "remove and replace".
Options Compared in the Benchmark
In this benchmark, three options are compared:
container1.replaceChildren(...container2.children)
: This method replaces the child nodes of container1
with the child nodes of container2
.while (container1.firstChild) container1.removeChild(container1.firstChild);
and while (container2.firstChild) container1.appendChild(container2.firstChild);
(Test case "remove and insert"): These while loops remove child nodes from container1
and then append them to container1
.while (container1.firstChild) container1.removeChild(container1.firstChild);
followed by container1.replaceChildren(...container2.children)
(Test case "remove and replace"): This approach first removes all child nodes from container1
using a while loop, and then replaces the content of container1
with the child nodes of container2
.Pros and Cons of Each Approach
replaceChildren
: Pros:replaceChildren
.replaceChildren
.replaceChildren
(Test case "remove and replace"): Pros:Library Used
None of the test cases explicitly use a library. However, document.querySelector
is used to select DOM elements, which is a standard JavaScript API.
Special JS Feature or Syntax
The benchmark does not require any special JavaScript features or syntax beyond basic DOM manipulation and while loops.
Other Alternatives
For clearing element content, other methods can be used:
innerHTML
property: container1.innerHTML = container2.innerHTML;
These alternatives may have different performance characteristics compared to the methods tested in this benchmark.