<div id="container"></div>
var container = document.getElementById('container');
var fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
var elements = [];
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
elements.push(li)
}
container.appendChild(fragment)
container.append(elements)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
appendChild fragment | |
appendChildren |
Test name | Executions per second |
---|---|
appendChild fragment | 9502907.0 Ops/sec |
appendChildren | 3244.1 Ops/sec |
I'd be happy to explain the benchmark being tested on MeasureThat.net.
Benchmark Purpose: The benchmark compares two approaches for appending elements to an HTML container:
DocumentFragment
object, populates it with 1000 HTML elements (li tags), and then appends the fragment to the container.append()
method.Options Comparison: The benchmark tests two options:
DocumentFragment
object and updating its contents, which may introduce overhead.Library: None of the benchmark code uses external libraries.
Special JS Feature/Syntax: The benchmark uses modern JavaScript features such as:
Item ${i}
).Other Alternatives: For appending elements to an HTML container, other alternatives could include:
innerHTML
or outerHTML
methods to append HTML strings directly to the container.appendChild()
.However, these approaches are generally considered less efficient than using a DocumentFragment
object or an array of elements with append()
method, especially for large datasets.
Benchmark Preparation Code: The provided script preparation code creates:
Individual Test Cases: The benchmark defines two test cases:
appendChild fragment
: Tests appending the fragment object to the container.appendChildren
: Tests appending the array of individual elements to the container using the append()
method.These test cases allow MeasureThat.net to compare the performance of these two approaches in a controlled environment.