<div id="wrap"></div>
const fragment = new DocumentFragment();
for (let i = 0; i < 1000; i++) {
const element = document.createElement('p');
fragment.appendChild(element);
}
document.querySelector("#wrap").appendChild(fragment);
const list = [];
for (let i = 0; i < 1000; i++) {
const element = document.createElement('p');
list.push(element);
}
document.querySelector("#wrap").append(list);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DocumentFragment append | |
(multiple) Node.append |
Test name | Executions per second |
---|---|
DocumentFragment append | 416.9 Ops/sec |
(multiple) Node.append | 211.3 Ops/sec |
I'll break down the benchmark and its test cases to explain what's being tested, compared, and considered.
Benchmark Overview
The benchmark measures the performance of two approaches for adding multiple elements to the DOM: using a DocumentFragment
and appending individual elements multiple times.
Script Preparation Code
There is no script preparation code provided. This means that the JavaScript engine should start with a clean slate, without any unnecessary overhead or setup.
Html Preparation Code
The HTML preparation code creates a basic structure:
<div id="wrap"></div>
This is used as a container for appending elements.
Individual Test Cases
There are two test cases:
DocumentFragment
to create a new, empty fragment:const fragment = new DocumentFragment();
for (let i = 0; i < 1000; i++) {
const element = document.createElement('p');
fragment.appendChild(element);
}
This approach allows for efficient batch appending of elements to the DOM. When appending multiple elements at once, the browser can optimize the process by reusing the DOM nodes and avoiding unnecessary DOM mutations.
const list = [];
for (let i = 0; i < 1000; i++) {
const element = document.createElement('p');
list.push(element);
}
document.querySelector("#wrap").append(...list);
This approach involves creating multiple DOM nodes and then appending them all at once using the append
method. While this might seem efficient, it can be slower than batch appending due to the overhead of creating individual DOM nodes.
Comparison
The benchmark compares the performance of these two approaches:
Pros and Cons
Pros of DocumentFragment append
:
Cons:
Pros of (multiple) Node.append
:
Cons:
Library Consideration
There is no specific library being used in this benchmark. However, using a DocumentFragment
requires some knowledge of the browser's internal DOM implementation and how fragments can be efficiently batch appended.
Special JS Feature or Syntax
The benchmark uses modern JavaScript features like:
const
declarations=>
)These features are widely supported in modern browsers, but may not work in older browsers.