const tpl = document.createElement('template');
tpl.innerHTML = `
<div>
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<button>Button</button>
</div>
`;
document.documentElement.appendChild(tpl.content);
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);
document.documentElement.appendChild(fragment);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
template | |
DocumentFragment |
Test name | Executions per second |
---|---|
template | 54513.0 Ops/sec |
DocumentFragment | 53055.3 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The benchmark compares two approaches for rendering HTML content:
innerHTML
to set the content of a template element (template
) directly.DocumentFragment
element and appending child elements to it, then appending the fragment to the document's body.Pros/Cons of each approach
Pros:
Cons:
innerHTML
)Pros:
innerHTML
since it avoids creating unnecessary DOM nodesCons:
Library/Technology Used
In both test cases, the following libraries/technologies are used:
innerHTML
is a built-in JavaScript method for setting the content of an element.DocumentFragment
is a standard HTML element that allows you to group multiple elements together without actually rendering them in the DOM.No external libraries or frameworks are explicitly mentioned.
Special JS Features/Syntax
The benchmark uses a feature called template literals, which was introduced in ECMAScript 2015 (ES6). Template literals allow you to embed expressions inside string literals, making it easier to create complex HTML strings. This feature is not specific to the benchmark but is used in the innerHTML
assignment.
Alternative Approaches
Other approaches that could be compared include:
createElementAndInsert
instead of appendChild
for better performance.Keep in mind that these alternative approaches might introduce additional complexity, dependencies, or overhead compared to the simple innerHTML
and DocumentFragment
methods used in this benchmark.