<div id='test-element'></div>
var elements = [document.createElement('div'), document.createElement('div')];
var fragment = document.createDocumentFragment();
var container = document.getElementById('test-element');
elements.forEach(element => fragment.appendChild(element));
container.appendChild(fragment);
var changeIndex = 1;
elements[changeIndex] = document.createElement('div');
container.replaceChild(elements[changeIndex], container.children[changeIndex]);
var changeIndex = 1;
var newChildren = document.createDocumentFragment();
elements[changeIndex] = document.createElement('div');
elements.forEach(element => newChildren.appendChild(element));
while(container.firstChild) {
container.firstChild.remove();
}
container.appendChild(newChildren)
var changeIndex = 1;
elements[changeIndex] = document.createElement('div');
container.replaceChildren(elements)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Cherrypick append child | |
Using documentFragment, append new & reuse old children | |
replaceChildren method |
Test name | Executions per second |
---|---|
Cherrypick append child | 765693.4 Ops/sec |
Using documentFragment, append new & reuse old children | 400501.4 Ops/sec |
replaceChildren method | 813957.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three different approaches to replace or append child nodes to an HTML element:
replaceChild
(Method 1)documentFragment
to append new children while reusing old ones (Method 2)replaceChildren
method (Method 3)Options Compared
The benchmark compares three approaches:
replaceChild
for larger sets of children, reduces unnecessary DOM mutations.replaceChild
.Library Usage
None of the benchmark methods explicitly use any libraries. However, they do rely on the browser's built-in DOM APIs.
Special JS Features or Syntax
No special JavaScript features or syntax are used in this benchmark. It only relies on standard DOM APIs and variable declarations.
Other Alternatives
Other approaches to replacing or appending child nodes could be considered:
appendChild
repeatedly (inefficient, as it creates a new parent node each time).Keep in mind that these alternatives may not be more efficient or practical for real-world scenarios, and the benchmark is primarily designed to compare the performance of these three specific methods.