const targetElem = document.createElement( 'DIV' );
targetElem.id = 'target';
targetElem.innerHTML = `
<div>
<span>Child 1</span>
</div>
<div>
<span>Child 2</span>
</div>
<div>
<span>Child 3</span>
</div>
`;
document.body.appendChild( targetElem );
document.getElementById('target').innerHTML = `
<div>
<span>Child 4</span>
</div>
`;
const target = document.getElementById('target')
target.replaceChildren();
target.insertAdjacentHTML( 'beforeend', `
<div>
<span>Child 4</span>
</div>
` );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
replaceChildren + insertAdjacentHTML |
Test name | Executions per second |
---|---|
innerHTML | 28640.8 Ops/sec |
replaceChildren + insertAdjacentHTML | 21128.2 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition JSON
The benchmark measures the performance of two approaches to update the content of an HTML element:
innerHTML
: Using the innerHTML
property to set the new content directly on the DOM element.replaceChildren + insertAdjacentHTML
: Replacing the existing children of the element with a new HTML fragment using replaceChildren()
and then inserting additional content using insertAdjacentHTML()
.Options Compared
The two options are compared in terms of their performance impact on the browser's execution speed.
Pros and Cons of Each Approach:
innerHTML
replaceChildren + insertAdjacentHTML
insertAdjacentHTML()
can be optimized by the browser, as it allows for incremental updates rather than full page reflows.Library/Functionality Used
None are explicitly mentioned in the benchmark definition JSON. However, the replaceChildren()
function is a built-in method of HTML elements in JavaScript, while insertAdjacentHTML()
is also part of the DOM API.
Special JS Feature/Syntax (if applicable)
There is no special JS feature or syntax used in this benchmark. The code uses standard JavaScript features and APIs.
Alternatives
Other approaches to update the content of an HTML element could include:
appendChild()
: Creating a new child node and appending it to the existing children.Keep in mind that these alternatives may introduce additional complexity or overhead, and their performance characteristics would need to be evaluated separately.