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.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) | 131.6 Ops/sec |
innerHTML | 99.1 Ops/sec |
The benchmark represented in the provided JSON measures the performance of two different methods for inserting a large block of HTML content into the Document Object Model (DOM) of a web page: using cloneNode(true)
and setting innerHTML
.
cloneNode(true)
:
div.append(temp.content.cloneNode(true));
<template>
element. The true
argument indicates that all descendants of the cloned node will also be cloned. It appends the cloned node to the target div
.innerHTML
:
div.innerHTML = res;
div
directly, replacing the existing content with the specified HTML string (res
).cloneNode(true)
Pros:
Cons:
innerHTML
, especially with substantial and deeply nested DOM trees.innerHTML
Pros:
innerHTML
is typically faster for large amounts of HTML since it's essentially a single operation that performs a bulk replacement of the inner content, thus avoiding individual node manipulations.innerHTML
is easy to write and understand.Cons:
innerHTML
with untrusted content can introduce security vulnerabilities if input is not properly sanitized.In the benchmark results:
cloneNode(true)
method achieved approximately 131.56 executions per second.innerHTML
method achieved approximately 99.11 executions per second.From these results, we can conclude that, in this case, cloneNode(true)
performed better than setting innerHTML
despite its potential overhead. This may be due to the relatively simple structure being cloned and the optimizations present in the JavaScript engine for handling cloneNode()
operations.
DocumentFragment
can help minimize reflows and repaints by allowing multiple DOM manipulations before a single insert operation.innerHTML
for adding new content rather than replacing existing content.These alternatives offer different trade-offs that could provide better performance depending on the specific context and use cases.