<div id='test'></div>
const fragment = document.createDocumentFragment()
for (i = 0; i < 1000; i++) {
const innerDiv = document.createElement("div");
innerDiv.className = "MyClass"
fragment.appendChild(innerDiv);
}
document.getElementById("test").append(fragment);
html = ""
for (i = 0; i < 1000; i++) {
html += "<div class='MyClass'></div>";
}
document.getElementById("test").insertAdjacentHTML("beforeend", html);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DocumentFragment | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
DocumentFragment | 590.6 Ops/sec |
insertAdjacentHTML | 934.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches for inserting HTML content into a DOM node: using document.createDocumentFragment()
(also known as Document Fragment) and using insertAdjacentHTML()
. The test case consists of creating 1000 elements with a class "MyClass" and appending them to the fragment. The resulting fragment is then appended to the DOM element with id "test".
Options Compared
The two options being compared are:
document.createDocumentFragment()
object, which allows you to add multiple elements to it without increasing the DOM's complexity. When the fragment is ready, you can append it to the DOM using the appendChild()
method.insertAdjacentHTML()
method of the DOM element, which inserts HTML content into the element at a specific position (in this case, "beforeend").Pros and Cons
Here's a brief summary of the pros and cons of each approach:
insertAdjacentHTML()
.Library
In this benchmark, no library is explicitly mentioned. However, it's worth noting that insertAdjacentHTML()
was introduced in ECMAScript 2015 (ES6) as a part of the HTML5 specification.
Special JS Feature/Syntax
The benchmark uses ES6 syntax, specifically template literals (\r\nfor (i = 0; i < 1000; i++) {\r\n html += \"<div class='MyClass'></div>\";\r\n}\r\n\r\ndocument.getElementById(\"test\").insertAdjacentHTML(\"beforeend\", html);
) and the spread operator (const fragment = document.createDocumentFragment()...
), which is also an ES6 feature.
Other Alternatives
If you're interested in exploring other alternatives, here are a few options:
innerHTML
instead of insertAdjacentHTML()
or appendChild()
.Keep in mind that each alternative has its own trade-offs, pros, and cons.