const tpl = document.createElement('template');
tpl.innerHTML = `
<div>
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<button>Button</button>
</div>
`;
const el = tpl.content.firstElementChild
function createByCloneNode() {
return el.cloneNode()
}
function createByDocumentFragment() {
const fragment = document.createDocumentFragment();
const el = document.createElement('div');
const heading = document.createElement('h1');
const para1 = document.createElement('p');
const para2 = document.createElement('p');
const button = document.createElement('button');
heading.innerText = 'Heading';
para1.innerText = 'Paragraph 1';
para2.innerText = 'Paragraph 2';
button.innerText = 'Button';
el.appendChild(heading);
el.appendChild(para1);
el.appendChild(para2);
el.appendChild(button);
fragment.appendChild(el);
return fragment
}
for (var i = 0; i < 1000; i++) {
document.documentElement.appendChild(createByCloneNode());
}
for (var i = 0; i < 1000; i++) {
document.documentElement.appendChild(createByDocumentFragment());
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
cloneNode | |
DocumentFragment |
Test name | Executions per second |
---|---|
cloneNode | 732.1 Ops/sec |
DocumentFragment | 119.9 Ops/sec |
What is tested on the provided JSON?
The provided JSON represents a benchmark test for two different approaches to create and append elements to the document body:
cloneNode()
method of an HTML element to create a copy of the original element, which is then appended to the document body.DocumentFragment
object to group multiple elements together, which is then appended to the document body.Options compared:
The benchmark compares the performance of these two approaches:
Pros and Cons:
cloneNode
, as it only creates a single DOM node that contains all the appended elements. This can lead to better performance when appending many elements.DocumentFragment
object.Library and Purpose:
The benchmark uses the following libraries:
template
element is used by Chrome, which has some caching mechanisms for template
elements. The DocumentFragment
API is a native Web APIs.Special JS feature or syntax:
There are no special JavaScript features or syntaxes used in this benchmark.
Benchmark Preparation Code:
The script preparation code creates an HTML template with a <div>
element and some text content, and then extracts the first child element of the template's content
property. This is used as a reusable function to create new elements for cloning or appending to the document body.
Individual test cases:
DocumentFragment
object, containing the extracted element, to the document body.Other alternatives:
Other approaches could be used instead of cloneNode
and DocumentFragment
, such as:
createElement()
and appending elements directly to the document body.Keep in mind that these alternatives would likely have different performance characteristics and might not be suitable for all use cases.