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
document.documentElement.appendChild(el.cloneNode());
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 | 97746.4 Ops/sec |
DocumentFragment | 103056.7 Ops/sec |
I'll break down the provided benchmark and its options, pros, cons, and other considerations.
Benchmark Overview
The benchmark compares two approaches: using an HTML template (innerHTML
) versus using a DocumentFragment
to render dynamic content.
Options Compared
innerHTML
):innerHTML
for complex templates with nested elements.innerHTML
.Library Used
In both test cases, the createDocumentFragment()
method is used. A DocumentFragment
is a container that holds a subset of the DOM tree. It's useful for optimizing performance by allowing you to update the fragment and then appending it to the document at once, rather than updating individual elements.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes mentioned in this benchmark.
Benchmark Preparation Code
The preparation code is empty, as required by MeasureThat.net. This means that the test case starts from a clean slate, without any pre-existing DOM elements or context.
Other Alternatives
Other approaches to rendering dynamic content include:
Keep in mind that each approach has its pros and cons, and the choice of which one to use depends on the specific requirements of your project, including performance, complexity, and maintainability.