const list = [];
let n = 0;
while(true) {
n++;
const div = document.createElement('div');
const p = document.createElement('p');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(p);
list.push(div);
if(n===100000)
break;
}
const list = [];
let n = 0;
const div = document.createElement('div');
const p = document.createElement('p');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(p);
while(true) {
n++;
list.push(div.cloneNode(false));
if(n===100000)
break;
}
const list = [];
let n = 0;
while(true) {
n++;
const div = document.createElement('div');
div.innerHTML = '<p class="font-bold">Hello!</p>';
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.3 Ops/sec |
cloneNode (deep) | 14.1 Ops/sec |
innerHTML | 1.9 Ops/sec |
This benchmark tests three different methods of creating new DOM elements in JavaScript and compares their performance:
1. createElement
:
<div>
element using document.createElement('div')
, adds a child <p>
element, sets its text content, and appends the paragraph to the div. This is repeated for 100,000 elements.2. cloneNode(false)
:
<div>
element initially, adds a child <p>
element with text content as before. Then, it uses div.cloneNode(false)
(which creates a shallow copy) repeatedly to add new div elements to the list.createElement
if you're working with complex elements that already have content and attributes set. 3. innerHTML
:
<div>
element using document.createElement('div')
, then sets its inner HTML content to <p class="font-bold">Hello!</p>
.Alternatives (Not tested in this benchmark):
innerHTML
depending on the complexity of your content.Considerations for Choosing a Method:
createElement
is often the fastest. For complex elements, cloneNode(false)
might offer performance gains if you're reusing the same structure repeatedly.Remember, benchmarking results can vary depending on factors like browser, device, and JavaScript engine.