<section id="container"></section>
let fragment = document.createDocumentFragment();
let elem = document.createElement("div");
for (let i = 0; i < 100; i++) {
fragment.appendChild(elem);
elem = elem.cloneNode();
}
let container = document.getElementById("container");
container.appendChild(elem)
let fragment = document.createDocumentFragment();
let elem = document.createElement("div");
for (let i = 0; i < 100; i++) {
fragment.appendChild(elem);
elem = elem.cloneNode();
}
let container = document.createElement("section");
container.appendChild(elem)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
appendChild to fragment, then append after getElementById (with cloneNode) | |
appendChild to fragment, then append after createElement (with cloneNode) |
Test name | Executions per second |
---|---|
appendChild to fragment, then append after getElementById (with cloneNode) | 16487.8 Ops/sec |
appendChild to fragment, then append after createElement (with cloneNode) | 14868.2 Ops/sec |
Let's dive into the benchmark and explore what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches for appending HTML elements to a document:
document.createElement("div")
fragment after creating the element using document.createElement
.document.createElement("section")
container after creating the element using document.createElement
.Options Compared
The benchmark is testing two options:
fragment
created using document.createDocumentFragment()
before appending to an element.element
created using document.createElement()
before appending to another element.Library and Purpose
The benchmark uses two built-in JavaScript libraries:
document.createDocumentFragment()
: Creates an empty document fragment that can be used as a container for elements. The purpose is to optimize appending to fragments, reducing the number of DOM mutations.document.createElement()
: Creates a new HTML element. In this case, it's used to create two separate containers (a div
and a section
) for appending elements.Special JS Features or Syntax
There are no special JavaScript features or syntax mentioned in the benchmark definition or test cases.
Other Alternatives
If you're interested in exploring alternative approaches, here are some options:
$()
function to create elements and manipulate the DOM.requestAnimationFrame()
for animations.Keep in mind that these alternatives may introduce additional complexity, dependencies, or performance overhead compared to the built-in JavaScript libraries used in this benchmark.