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 t = document.getElementById( 'target' );
const l = t.children.length;
for (let i = 0; i < l; i++) {
t.children[i].remove();
}
t.insertAdjacentHTML( 'afterbegin', `
<div>
<span>Child 4</span>
</div>
` );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
insertAdjacentHTML with remove |
Test name | Executions per second |
---|---|
innerHTML | 56391.5 Ops/sec |
insertAdjacentHTML with remove | 710.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is testing two different approaches to inserting HTML content into a DOM element:
innerHTML
:<div>
element with child elements, which is then appended to the document body.innerHTML
property of an element with the ID "target" to add a new child element.insertAdjacentHTML
with remove
:insertAdjacentHTML
instead of updating the innerHTML
directly.Options being compared
The benchmark is comparing two approaches:
innerHTML
property of an element to insert new content.insertAdjacentHTML
method with a remove
attribute to clear and then re-insert content.Pros and Cons
Here are some pros and cons of each approach:
Direct innerHTML
Pros:
insertAdjacentHTML
Cons:
insertAdjacentHTML
with remove
Pros:
afterbegin
attribute).Cons:
insertAdjacentHTML
) which can introduce overhead.Library usage
There is no explicit library mentioned in the benchmark definition or test cases. However, it's worth noting that insertAdjacentHTML
was introduced in HTML5 as a way to insert content at specific positions in the DOM tree.
Special JavaScript features/syntax
There are no special JavaScript features or syntax mentioned in this benchmark.
Other alternatives
If you're interested in exploring alternative approaches, here are a few options:
createElement()
and then setting its innerHTML
property (as shown in the script preparation code).textContent
instead of innerHTML
for inserting content.Keep in mind that these alternatives might have different performance characteristics or require more complex code to manage.
I hope this explanation helps you understand what's being tested in this benchmark!