const list = [];
let n = 0;
while(true) {
n++;
const div = document.createElement('div');
const div2 = document.createElement('div');
const div3 = document.createElement('div');
const p = document.createElement('p');
div2.classList.add('two');
div3.classList.add('three');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(div2);
div2.appendChild(div3);
div3.appendChild(p);
list.push(div);
if(n===100000)
break;
}
const list = [];
let n = 0;
const div = document.createElement('div');
const div2 = document.createElement('div');
const div3 = document.createElement('div');
const p = document.createElement('p');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(div2);
div2.appendChild(div3);
div3.appendChild(p);
while(true) {
n++;
list.push(div.cloneNode(true));
if(n===100000)
break;
}
const list = [];
let n = 0;
while(true) {
n++;
const div = document.createElement('div');
div.innerHTML = '<div class="two"><div class="three"><p class="font-bold">Hello!</p></div></div>';
list.push(div);
if(n===100000)
break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
cloneNode (deep) | |
innerHTML |
Test name | Executions per second |
---|---|
createElement | 2.5 Ops/sec |
cloneNode (deep) | 9.9 Ops/sec |
innerHTML | 3.7 Ops/sec |
Let's dive into the benchmark.
What is being tested?
The benchmark tests three ways to create new DOM elements: createElement
, cloneNode
(specifically, cloneNode(true)
which clones the element deeply), and innerHTML
. The test case creates a specific structure with multiple nested div
and p
elements, adds some classes to them, sets their text content, and appends them to each other in a loop. This is done to create a large array of DOM elements that need to be pushed onto the list
.
Options being compared:
document.createElement
method.cloneNode(true)
method.Pros and Cons of each approach:
innerHTML
, as it only requires cloning an existing element and its children.Library used:
None explicitly mentioned. However, document.createElement
and cloneNode
are standard JavaScript methods that work across all browsers.
Special JS feature or syntax:
None mentioned in this benchmark.
Considerations:
innerHTML
may be affected by the browser's rendering engine, as it creates a new document object that needs to be parsed and rendered.cloneNode
method is more efficient for creating nested elements, but may be slower for single-level elements or those with complex structures.Alternatives:
innerHTML
, you could use template literals (e.g., ${element.innerHTML}
) to set content in a DOM element.cloneNode
or innerHTML
.Keep in mind that these alternatives may have different performance characteristics and might not be suitable for all use cases.