const div = document.createElement('div');
div.innerHTML = '<p>FIRMWARE WINDOW</p>';
const modal = document.createElement('div');
let n = 0;
while(true) {
n++;
const cloneText = div.innerHTML;
modal.innerHTML = cloneText;
if(n===100)
break;
}
const div = document.createElement('div');
div.innerHTML = '<p>FIRMWARE WINDOW</p>';
const modal = document.createElement('div');
let n = 0;
while(true) {
n++;
const cloneElement = div.cloneNode(true);
modal.replaceChildren(cloneElement);
if(n===100)
break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
cloneNode |
Test name | Executions per second |
---|---|
innerHTML | 14554.5 Ops/sec |
cloneNode | 20184.9 Ops/sec |
In the provided benchmark, two different approaches for updating the content of a DOM (Document Object Model) element in JavaScript are compared: using innerHTML
and using cloneNode
.
div
and assigns its innerHTML
to another div
(modal) in a loop. Specifically, it captures the HTML content of the original div
and reassigns it to the modal
div.div
, but it uses the cloneNode
method to create a deep copy of the div
. It then replaces the content of the modal with the cloned element.1. Using innerHTML
:
2. Using cloneNode
:
cloneNode
method and its parameters (deep vs shallow cloning).cloneNode
method performed better with 20,184.95 executions per second, compared to the innerHTML
method, which achieved 14,554.50 executions per second. This indicates that using cloneNode
is likely more efficient for this particular use case.cloneNode
is preferable.DocumentFragment
to reduce reflows and repaints when inserting multiple elements into the DOM.textContent
could be faster and more secure than innerHTML
.innerHTML
or cloneNode
, creating elements programmatically using document.createElement()
and appending them to the DOM can provide more control and potentially better performance, especially when combined with DocumentFragment
.In summary, both approaches have their use cases, but for this benchmark, cloneNode
demonstrated superior performance, highlighting its advantages in scenarios where the precise state of DOM elements needs to be preserved with minimal overhead.