<div id="test"></div>
newElement = document.createElement("div");
newElement.id = "testing"
for (i = 0; i < 1000; i++) {
let newElementPart = document.createElement("div");
newElementPart.classList.add("testClass");
newElement.append(newElementPart);
}
document.getElementById("test").append(newElement);
html = "<div id='testing'>"
for (i = 0; i < 1000; i++) {
html += "<div class='testClass'></div>";
}
html += "</div>";
document.getElementById("test").insertAdjacentHTML("beforeend", html);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
createElement | 573.1 Ops/sec |
insertAdjacentHTML | 979.7 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares two approaches to inserting or appending HTML content to an existing DOM element: createElement
and insertAdjacentHTML
. The benchmark aims to determine which approach is faster in creating 1000 elements with a specific class, and then appending those elements to another element.
Options Compared
Two options are compared:
div
element using the document.createElement()
method, adds a class, and then appends it to another element using the appendChild()
method.insertAdjacentHTML()
method.Pros and Cons
Library and Purpose
In the provided benchmark, there is no specific library being used. However, insertAdjacentHTML
does rely on the DOMTokenList
API, which is a part of the W3C standard for manipulating DOM tokens (e.g., classes, styles).
Special JavaScript Feature or Syntax
There isn't any special JavaScript feature or syntax mentioned in this benchmark.
Other Considerations
When choosing between these two approaches, consider the trade-offs:
createElement
might be a better choice.insertAdjacentHTML
could provide a performance benefit.Alternative Approaches
Other alternatives to these two approaches include:
${}
) to construct the HTML string directly.DOMParser
API to parse an HTML string and create DOM elements from it.However, for most cases, createElement
and insertAdjacentHTML
remain viable options due to their simplicity and performance characteristics.