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>
`;
document.getElementById( 'target' ).insertAdjacentHTML( 'afterend', `
<div>
<span>Child 4</span>
</div>
` );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
innerHTML | 114989.6 Ops/sec |
insertAdjacentHTML | 90260.2 Ops/sec |
Let's break down the provided benchmark and its various components.
Benchmark Definition
The benchmark is defined by the JSON object provided, which contains information about the benchmark itself. The key aspects of this definition are:
insertAdjacentHTML
and innerHTML
.targetElem
) with some initial HTML content. This code is executed before each test case.Individual Test Cases
The benchmark consists of two individual test cases:
innerHTML
property of an element (targetElem
) with a new HTML content.innerHTML
.targetElem
) after its content has been rendered, using the insertAdjacentHTML
method with the afterend
flag.Library: None
There are no external libraries used in this benchmark. Both test cases only utilize built-in JavaScript methods (innerHTML
and insertAdjacentHTML
) and the DOM API.
Special JS Feature/Syntax
None.
Options Compared
The two test cases compare the performance of:
innerHTML
property.insertAdjacentHTML
method with the afterend
flag.Pros and Cons
innerHTML:
Pros:
Cons:
insertAdjacentHTML
when updating large or complex HTML structuresinsertAdjacentHTML:
Pros:
innerHTML
for larger HTML updatesCons:
Other Considerations
When deciding between innerHTML
and insertAdjacentHTML
, consider the following factors:
insertAdjacentHTML
might be a better choice.insertAdjacentHTML
might be a better option.insertAdjacentHTML
can help.Alternative Approaches
Other alternatives for updating HTML content include:
with partial parsing
: You can use a partial parsing approach to update only the necessary parts of the existing HTML structure.innerHTML
or insertAdjacentHTML
, you can manually manipulate the DOM by creating and removing elements, or by using CSS transitions or animations to update the content.These alternatives might offer better performance or more control over the DOM updates, but they also add complexity and potential overhead compared to innerHTML
and insertAdjacentHTML
.