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>
<h3>Title</h3>
<div>
<span>Child 4</span>
</div>
`;
document.getElementById( 'target' ).insertAdjacentHTML( 'beforeend', `
<div>
<span>Child 4</span>
</div>
<h3>Title</h3>
<div>
<span>Child 4</span>
</div>
` );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
innerHTML | 102.2 Ops/sec |
insertAdjacentHTML | 203002.7 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of two JavaScript methods: insertAdjacentHtml
and innerHTML
. Both methods are used to append HTML content to an existing element, but they differ in how they handle the HTML string.
Options Compared
There are two options being compared:
Pros and Cons
Here are some pros and cons of each approach:
insertAdjacentHtml
because it requires creating a new string representation of the HTML content, which can lead to more memory allocation and garbage collection.innerHTML
, as it avoids creating a new string representation of the HTML content.Library Usage
In this benchmark, no libraries are explicitly mentioned. However, if we look at the Script Preparation Code
and Html Preparation Code
, we can see that the script creates a DIV
element with some HTML content using template literals (\r\n\t<div>\r\n\t\t<span>Child 1</span>\r\n\t</div>\r\n...
). This is not specific to any library, but rather a standard JavaScript way of creating and formatting strings.
Special JS Features or Syntax
There are no special JavaScript features or syntaxes being used in this benchmark. The code is standard JavaScript, using the features and methods that are widely supported across modern browsers.
Other Alternatives
If you're interested in alternative approaches for inserting HTML content into an element, here are a few options:
insertAdjacentHtml
, it can be slower and more complex to use.replace()
method on the innerHTML property of an element, but this approach is not recommended because it can lead to performance issues and security vulnerabilities.Overall, the benchmark compares two common approaches for inserting HTML content into an element: innerHTML
and insertAdjacentHtml
. While both methods have their pros and cons, insertAdjacentHtml
tends to be more efficient, making it a better choice when performance is critical.