document.body.innerHTML = "";
var root = document.createElement("div");
for (var i = 0; i < 10000; i++) {
var e = document.createElement("span");
e.innerText = i + " text";
root.appendChild(e);
}
document.body.appendChild(root);
var frag = document.createDocumentFragment();
for (var i = 0; i < 10000; i++) {
var e = document.createElement("span");
e.innerText = i + " text";
frag.appendChild(e);
}
document.body.appendChild(frag);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
createDocumentFragment |
Test name | Executions per second |
---|---|
createElement | 62.0 Ops/sec |
createDocumentFragment | 55.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The provided benchmark tests two approaches to append elements to a document: createElement
and createDocumentFragment
. The test creates 10,000 HTML elements (span) with incrementing text content and appends them to a container element using each approach. The benchmark measures the performance of these two approaches in terms of executions per second.
Options compared
The main difference between the two approaches is how they handle the creation and disposal of temporary objects:
createElement
: A new HTML element (span
in this case) is created on every iteration, which can lead to:createDocumentFragment
: A temporary fragment object is created, which contains the appended elements, reducing memory allocation and deallocation overhead. However, it still involves:Pros and Cons of each approach
createElement
:
Pros:
Cons:
createDocumentFragment
:
Pros:
Cons:
createDocumentFragment
is a part of the DOM API).Library and special JS features
The benchmark uses the following library:
document.createDocumentFragment()
: This method is part of the DOM API and creates a new fragment object that can be used to append elements without the overhead of creating multiple elements.There are no special JavaScript features used in this benchmark beyond what's standard for vanilla JavaScript and the DOM API.
Other alternatives
Some alternative approaches could include:
appendChild
with a single element: Instead of appending individual elements, you could create a single container element (e.g., a div
) and append all elements to it.innerHTML
: You could set the innerHTML
property of an element directly instead of using appendChild
.However, these alternatives would likely require significant changes to your codebase and may not be suitable for all use cases.
That's a wrap on this benchmark explanation!