<div id='messages'></div>
let list = document.getElementById("messages");
for(i=0; i<1000; i++) {
list.innerHTML += "<span>Text</span>"
}
let list = document.getElementById("messages");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
let list = document.getElementById("messages");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
document.getElementById("messages").innerHTML = "";
document.getElementById("messages").innerText = "";
document.getElementById("messages").textContent = "";
let list = document.getElementById("messages");
while (list.firstChild) {
list.firstChild.remove()
}
var range = new Range();
range.selectNodeContents(document.getElementById("messages"));
range.deleteContents();
let list = document.getElementById("messages");
list.replaceChildren()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Remove firstChild | |
Remove lastChild | |
innerHTML | |
innerText | |
textContent | |
firstChild.remove | |
range | |
replaceChildren |
Test name | Executions per second |
---|---|
Remove firstChild | 10291701.0 Ops/sec |
Remove lastChild | 10280178.0 Ops/sec |
innerHTML | 8593443.0 Ops/sec |
innerText | 7444265.0 Ops/sec |
textContent | 8397485.0 Ops/sec |
firstChild.remove | 10332918.0 Ops/sec |
range | 2685014.0 Ops/sec |
replaceChildren | 7788756.5 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark measures the performance of removing all children from a DOM element with the ID "messages". The script preparation code is used to populate the element with 1000 HTML spans, and then the benchmark starts. The HTML preparation code creates an empty <div>
element with the specified ID.
Test Cases
There are six test cases:
while
loop.innerHTML
property to an empty string.innerText
property instead of innerHTML
.firstChild
property (not available in older browsers).Options Compared
The benchmark is comparing different approaches for removing children from an HTML element:
firstChild
property, which may not be supported in older browsers. However, it's likely that this is included to ensure compatibility with newer browsers.Pros and Cons
Here are some pros and cons for each approach:
removeChild()
or the Web Range API, especially for larger amounts of data.removeChild()
, but it may be necessary for older browsers that don't support this property.Browser Considerations
The benchmark results are likely to be influenced by the specific browser being used. Some browsers may have better performance or compatibility with certain methods than others. For example:
firstChild.remove
or other compatibility fixes.Conclusion
The benchmark provides a good starting point for understanding the performance differences between various methods for removing children from an HTML element. However, it's essential to consider browser compatibility and use the most efficient method available for each specific use case.