<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.firstChild) node.firstChild.remove()
var node = document.getElementById('container');
node.innerText = '';
var node = document.getElementById('container');
node.textContent = '';
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild | |
remove | |
innerText | |
textContent |
Test name | Executions per second |
---|---|
innerHTML | 10123501.0 Ops/sec |
removeChild | 24866078.0 Ops/sec |
remove | 25181452.0 Ops/sec |
innerText | 7833074.5 Ops/sec |
textContent | 10897893.0 Ops/sec |
Benchmark Overview
The MeasureThat.net benchmark is designed to compare the performance of different approaches for removing or setting the inner content, text content, or child nodes of an HTML element in JavaScript.
Test Cases
There are six test cases:
innerHTML
: Sets the inner HTML of an element.removeChild
: Removes all child nodes from an element using a while loop.remove
: Removes a single child node from an element using a while loop.innerText
: Sets the text content of an element.textContent
: Sets the text content of an element.Comparison of Approaches
Here's a comparison of the different approaches:
remove()
on it. While this is faster than innerHTML
, it still requires iteration and can be slower for large datasets.removeChild
, but only removes a single child node instead of all of them.innerHTML
. However, it may not work correctly if the text content contains Unicode characters that require multiple code units to represent.innerText
, but takes into account Unicode characters and can handle more complex scenarios.Pros and Cons
Here are some pros and cons of each approach:
innerHTML
, can handle large datasets.innerText
or textContent
.removeChild
, but only removes a single node.innerHTML
, works well for text content scenarios.innerText
, handles Unicode characters and HTML tags better.removeChild
due to the additional processing required.Library and Special JS Features
No libraries are used in this benchmark. However, some special JavaScript features, such as support for Unicode characters (e.g., String.fromCodePoint()
), may affect the performance of certain approaches.
Alternatives
Other alternatives that could be tested in a similar benchmark include:
DOMParser
to parse and set HTML content.DocumentFragment
to create a temporary container and move nodes around.requestAnimationFrame
or other optimization techniques to improve performance.These alternatives could provide additional insights into the trade-offs between different approaches and help identify the most efficient way to perform common DOM manipulation tasks.