<div id="container"></div>
var elements = [document.createElement('div'), document.createElement('div')];
var fragment = document.createDocumentFragment();
var container = document.getElementById('container');
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;
elements[changeIndex] = document.createElement('div');
container.replaceChildren(elements)
var changeIndex = 1;
var newChildren = document.createDocumentFragment();
elements[changeIndex] = document.createElement('div');
elements.forEach(element => newChildren.appendChild(element));
container.replaceChildren(newChildren)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
replaceChild | |
replaceChildren | |
append documentFragment |
Test name | Executions per second |
---|---|
replaceChild | 1434729.0 Ops/sec |
replaceChildren | 575702.9 Ops/sec |
append documentFragment | 635970.6 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Goal
The benchmark measures the performance difference between three approaches for replacing or appending child elements to an HTML container:
replaceChild
replaceChildren
documentFragment
to append childrenOptions Compared
Each option is compared in terms of execution speed (measured as executions per second).
replaceChild
replaces the specified child element with a new one, and removes the old one from the DOM.
Pros:
Cons:
replaceChildren
replaces all child elements with a new set of children.
Pros:
Cons:
Using a documentFragment
to append children creates a new container element that holds all the child elements, which can then be appended to the parent element in one operation.
Pros:
Cons:
documentFragment
element.documentFragment
is not properly optimized (e.g., by using an efficient fragment creation algorithm).Libraries Used
None are explicitly mentioned in the provided benchmark definition. However, it's worth noting that some implementations of replaceChild
and replaceChildren
might rely on external libraries or frameworks for DOM manipulation.
Special JS Features/Syntax
There is no special JavaScript feature or syntax used in this benchmark. The code is standard JavaScript, with no references to advanced features like async/await, promises, or modern ES6+ syntax.
Other Alternatives
Some alternative approaches to replacing or appending child elements include:
insertBefore
or insertAfter
instead of replaceChild
Keep in mind that these alternatives might have different performance characteristics, trade-offs, or use cases compared to the options being tested in this benchmark.