var str = `<div>${Math.random().toString().slice(2)}</div>`;
var temp = document.createElement('template')
var res = '';
for(i=0; i<30000; i++){
res += str
}
temp.innerHTML = res;
var div = document.createElement('div')
div.innerHTML = res;
div.innerHTML = res;
div.append(temp.content.cloneNode(true));
div.innerHTML = res;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
cloneNode(true) | |
innerHTML |
Test name | Executions per second |
---|---|
cloneNode(true) | 53.3 Ops/sec |
innerHTML | 114.3 Ops/sec |
The provided benchmark tests two different methods of inserting content into the DOM in JavaScript: using innerHTML
and using cloneNode(true)
in conjunction with innerHTML
. Here's a detailed breakdown of the benchmark, including the pros and cons of each approach, the libraries (if any) involved, and alternative methods.
Method 1: innerHTML
div.innerHTML = res;
<div>
element by assigning it a string of HTML (res
).Pros:
Cons:
innerHTML
can lead to losing event handlers attached to child elements since it reconstructs the entire content of the element.Method 2: cloneNode(true)
div.append(temp.content.cloneNode(true));
template
element that holds the constructed HTML. The content of this template is then cloned into the target <div>
. The cloneNode(true)
method creates a deep clone of the node, copying all child nodes.Pros:
cloneNode(true)
provides more fine-grained control over what is appended and allows for reusing DOM elements efficiently.Cons:
innerHTML
, as it involves the cloning process in the context of the DOM tree.From the benchmark results:
innerHTML
method executed approximately 114.34 operations per second.cloneNode(true)
method executed approximately 53.26 operations per second.This indicates that using innerHTML
is significantly faster than the cloning method for this specific use case of inserting large amounts of HTML content.
cloneNode(true)
may be more suitable despite its performance overhead.In summary, this benchmark illustrates the trade-offs between speed and manageability when interacting with the DOM in JavaScript. For applications where performance is critical, direct methods like innerHTML
may be the preferred option, whereas cloneNode(true)
may be beneficial in more complex scenarios requiring event management.