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===1)
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(true));
if(n===1)
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===1)
break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
cloneNode (deep) | |
innerHTML |
Test name | Executions per second |
---|---|
createElement | 823860.4 Ops/sec |
cloneNode (deep) | 566901.6 Ops/sec |
innerHTML | 489268.0 Ops/sec |
Let's break down the provided JSON data and explain what's being tested.
Benchmark Overview
The benchmark is comparing three different approaches to create new DOM elements:
createElement
: Creating a new element using the document.createElement
method.cloneNode (deep)
: Cloning an existing element using the cloneNode
method with the true
argument, which indicates deep cloning.innerHTML
: Setting the inner HTML of an element.Test Cases
Each test case is a separate benchmark that measures the performance of one of these approaches. Here's what each test case does:
div
element and appends a p
element to it using appendChild
. The resulting elements are pushed into the list.div
element using cloneNode(true)
. This creates a deep clone of the original element, which includes all its child nodes and attributes.div
element to contain a p
element with the text "Hello!". The resulting elements are pushed into the list.Library and Special JS Features
Comparison of Approaches
The pros and cons of each approach are:
Other Alternatives
There are other approaches that could be used in place of these methods:
appendChild
or innerHTML
, a fragment could be created using document.createDocumentFragment
to improve performance.requestAnimationFrame
to schedule the creation and appending of elements, which can help avoid blocking the main thread.However, these alternatives would likely require significant changes to the benchmark code and might not provide noticeable performance improvements for most use cases.