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( 'beforeend', `
<div>
<span>Child 4</span>
</div>
` );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
innerHTML | 9.2 Ops/sec |
insertAdjacentHTML | 28948.9 Ops/sec |
Let's break down the provided benchmark and explain what is tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark measures the performance difference between two HTML manipulation methods:
insertAdjacentHTML
: A method that inserts HTML into an element using the insertAdjacentHTML()
method.innerHTML
: A method that sets or gets the HTML content of an element's innerHTML property.Script Preparation Code
The script preparation code creates a new <div>
element, appends it to the document body, and sets its innerHTML with some sample HTML content:
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);
Html Preparation Code
The html preparation code is empty, which means that the benchmark focuses on the JavaScript execution time, without considering any additional HTML parsing or compilation overhead.
Individual Test Cases
There are two test cases:
innerHTML +=
.insertAdjacentHTML()
with the 'beforeend'
flag.Options Compared
The two options being compared are:
insertAdjacentHTML()
method.Pros and Cons
Here are some pros and cons for each option:
innerHTML
Pros:
Cons:
insertAdjacentHTML
Pros:
insertAdjacentHTML()
is designed to insert HTML into an element efficiently, without the need for parsing or compiling the new content.innerHTML
, as it allows you to specify a fragment of the DOM tree where the new content will be inserted.Cons:
insertAdjacentHTML()
method is less widely supported and understood than innerHTML
.Other Considerations
When choosing between these two options, consider the specific use case:
insertAdjacentHTML()
might be a better choice.innerHTML
might be sufficient.Keep in mind that both methods have their trade-offs, and the benchmark results will help determine which one is faster in your specific use case.