<div id="container"></div>
const node = document.getElementById('container');
const fragment = document.createDocumentFragment();
for(let i = 0; i < 10000; i++) {
node.appendChild(document.createElement('div'));
fragment.appendChild(document.createElement('div'));
}
const node = document.getElementById('container');
const fragment = document.createDocumentFragment();
for(let i = 0; i < 10000; i++) {
fragment.appendChild(document.createElement('div'));
}
while (node.firstChild) {
node.removeChild(node.lastChild);
}
node.appendChild(fragment);
const node = document.getElementById('container');
const fragment = document.createDocumentFragment();
for(let i = 0; i < 10000; i++) {
fragment.appendChild(document.createElement('div'));
}
node.replaceChildren(fragment);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
while w/ appendChild | |
replaceChildren |
Test name | Executions per second |
---|---|
while w/ appendChild | 118.3 Ops/sec |
replaceChildren | 138.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches for removing and replacing child nodes in an HTML element:
replaceChildren
(Method 1)while
loop with appendChild
(Method 2)What's Being Tested
In both methods, the goal is to create a large number of DOM elements (div
) and append them to two separate containers: node
and fragment
. Then, one of the methods is used to remove all child nodes from node
, and the remaining fragment is appended back to node
.
Method 1: replaceChildren
This method uses the replaceChildren()
method on the node
element, which replaces its child nodes with a new set of child nodes. The fragment containing the elements is passed as an argument.
Pros and Cons
Pros:
Cons:
Method 2: while loop with appendChild
This method uses a while
loop to repeatedly remove child nodes from node
using removeChild()
and append new elements to both node
and fragment
using appendChild()
. The loop continues until all child nodes have been removed.
Pros:
Cons:
Library Usage
In both benchmark definitions, the document
object is used to access HTML elements and methods. Specifically:
document.getElementById()
is used to retrieve an element by its ID.document.createDocumentFragment()
is used to create a new document fragment for storing child nodes.appendChild()
and removeChild()
are used to manipulate the DOM.Special JS Features or Syntax
None mentioned in the provided benchmark definitions. However, it's worth noting that other JavaScript features, such as for...of
loops, async/await, or modern ES6+ syntax, might be used in other benchmarks to test specific browser capabilities.
Alternatives
Other alternatives for removing and replacing child nodes include:
requestAnimationFrame()
or setTimeout()
to optimize DOM updates.Keep in mind that the choice of approach depends on the specific use case, browser requirements, and desired performance characteristics.