document.body.innerHTML = "";
var root = document.createElement("div");
document.body.appendChild(root);
for (var i = 0; i < 1000; i++) {
var e = document.createElement("span");
e.innerText = i + " text";
root.appendChild(e);
}
var frag = document.createDocumentFragment();
var root = document.createElement("div");
for (var i = 0; i < 1000; i++) {
var e = document.createElement("span");
e.innerText = i + " text";
root.appendChild(e);
}
document.body.appendChild(frag);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
createDocumentFragment |
Test name | Executions per second |
---|---|
createElement | 1462.4 Ops/sec |
createDocumentFragment | 953.8 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark compares two approaches for creating elements in a web page:
document.createElement
: This method creates a new HTML element and returns it as a reference to that element.document.createDocumentFragment
: This method creates a new document fragment, which is an immutable container for holding multiple child nodes.Options compared
The benchmark compares the performance of these two approaches on the same test case:
div
element with 1000 span
elements) is created using both methods.body
of the document.Pros and Cons of each approach
document.createElement
:document.createDocumentFragment
:Library usage
In this benchmark, the createDocumentFragment
method uses the document.createDocumentFragment()
method, which is a standard HTML5 API. This method creates a new document fragment and returns it as a reference to that fragment.
Special JS feature or syntax
There are no special JavaScript features or syntaxes used in this benchmark beyond what's commonly available in modern JavaScript implementations.
Other alternatives
If you're looking for alternative approaches, consider the following:
Keep in mind that these alternatives may introduce additional dependencies, complexity, or trade-offs in terms of performance and learnability.