<div id='x'></div>
const root = document.getElementById('x');
for (let i = 0; i < 100; i++) {
let notRoot = document.createElement('div')
notRoot.innerHTML = `the rainbow eats sunlight under jupiter's moonlight ${Math.random()}`;
root.appendChild(notRoot);
}
const root = document.getElementById('x').cloneNode(true);
root.innerHTML = '';
const root = document.getElementById('x').cloneNode(true);
while (root.firstChild)
root.removeChild(root.firstChild);
const root = document.getElementById('x').cloneNode(true);
while (root.lastChild)
root.removeChild(root.lastChild);
const root = document.getElementById('x').cloneNode(true);
root.textContent = '';
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild firstChild | |
removeChild lastChild | |
textContent |
Test name | Executions per second |
---|---|
innerHTML | 10131.4 Ops/sec |
removeChild firstChild | 6893.2 Ops/sec |
removeChild lastChild | 6915.7 Ops/sec |
textContent | 11305.0 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The benchmark is designed to test the performance of different methods for clearing HTML element children in JavaScript. The script preparation code creates an HTML element with 100 child elements, each containing a random string. The innerHTML
property is set to an empty string using three different approaches:
cloneNode(true)
: Creates a deep copy of the original element and sets its innerHTML
to an empty string.removeChild
+ firstChild
or lastChild
: Removes the first or last child element from the list, respectively.Options Compared
The benchmark compares the performance of three different approaches:
innerHTML
to an empty string.removeChild
method with either firstChild
or lastChild
as the argument.Pros and Cons
Library Used
None, this benchmark is a basic test of JavaScript's DOM manipulation capabilities.
Special JS Feature/Syntax
There are no special features or syntax used in this benchmark. It only relies on standard JavaScript and DOM APIs.
Other Considerations
The benchmark measures the time taken for each approach to execute 100 times. The results show that cloneNode(true)
is the fastest method, followed by removeChild lastChild
, and then removeChild firstChild
.
Alternatives
If you want to explore alternative approaches or libraries, consider the following options:
Keep in mind that this benchmark is designed to illustrate basic concepts and may not reflect real-world scenarios. The actual performance differences between these approaches will depend on the specific use case, JavaScript version, and environment.