<form id='test'></form>
const htmlStrg = `<fieldset class='grid-container'><div class='cell'><input type='date' name='date' class='input input-date'></div></fieldset>`
const parsedHTML = new DOMParser().parseFromString(htmlStrg, 'text/html').body.firstChild
const form = document.getElementById('test')
for (let i = 0; i < 200; i++) {
form.appendChild(parsedHTML.cloneNode(true))
}
const htmlStrg = `<fieldset class='grid-container'><div class='cell'><input type='date' name='date' class='input input-date'></div></fieldset>`
const form = document.getElementById('test')
for (let i = 0; i < 200; i++) {
form.insertAdjacentHTML('beforeend', htmlStrg)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
append cloneNode | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
append cloneNode | 6.0 Ops/sec |
insertAdjacentHTML | 1.8 Ops/sec |
I'd be happy to help explain the provided benchmark.
What is tested:
The benchmark tests two different ways of inserting HTML content into a form
element in JavaScript:
fieldset
element) and appends it to another element (form
). The cloned element is then appended multiple times (200 times) to the form.form
element.Options compared:
The two methods are compared in terms of their performance:
Other considerations:
When choosing between these methods, consider the following factors:
insertAdjacentHTML
might be a better choice since it avoids creating multiple DOM elements.append cloneNode
might be faster for smaller numbers of cloned elements. However, as the number of cloned elements increases, insertAdjacentHTML
may become more efficient.append cloneNode
is a better choice.Library usage:
There is no library explicitly mentioned in the benchmark definition. However, the use of DOMParser
suggests that JavaScript's built-in DOM APIs are being utilized to parse and manipulate HTML content.
Special JS feature or syntax:
There are no special JavaScript features or syntaxes used in this benchmark. The focus is on comparing the performance of two fundamental methods for inserting HTML content into a form element.
Alternatives:
If you're considering alternative approaches, here are a few:
insertAdjacentHTML
, but with less control over the inserted element's properties.innerHTML
, but only for text content; not suitable for inserting HTML elements.Keep in mind that each of these alternatives has its own trade-offs and performance characteristics.