<div id="test"></div>
let newElement = document.createElement("div");
let DOM = document.body;
for (i = 0; i < 1000; i++) {
DOM.append(newElement);
}
let newElement = "<div></div>"
let DOM = document.body;
for (i = 0; i < 1000; i++) {
DOM.insertAdjacentHTML("beforeend", newElement);
}
let fragment_VDOM = document.createDocumentFragment();
let newElement = document.createElement("div");
let DOM = document.body;
for (i = 0; i < 1000; i++) {
fragment_VDOM.appendChild(newElement);
DOM.appendChild(fragment_VDOM);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
append | |
insertAdjacentHTML | |
appendChild (createDocumentFragment) |
Test name | Executions per second |
---|---|
append | 1474.4 Ops/sec |
insertAdjacentHTML | 291.2 Ops/sec |
appendChild (createDocumentFragment) | 1008.1 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
The provided JSON represents three test cases, each comparing different approaches to append or insert HTML content into a web page:
body
element using DOM.append()
.DOM.insertAdjacentHTML()
with the beforeend
argument.createDocumentFragment()
object and then appending that fragment to the body
element.Now, let's discuss the pros and cons of each approach:
createDocumentFragment()
object allows you to batch together multiple DOM operations and then apply them all at once, reducing the overall number of DOM updates.Pros:
Cons:
Other considerations:
insertAdjacentHTML
method uses a more efficient algorithm to traverse the DOM tree, which can result in better performance on large documents.insertAdjacentHTML
. This can reduce the overhead of repeated calls to this function.In terms of special JS features or syntax, there aren't any explicitly mentioned. However, it's worth noting that the use of createDocumentFragment()
requires a good understanding of how DOM fragments work and when they should be used.
The benchmark results show that:
Other alternatives that could be considered for similar benchmarking include:
DOM.insertAdjacentElement()
instead of insertAdjacentHTML
DOM.appendChild()
, DOM.removeChild()
)