const template = document.createElement("template");
template.innerHTML = "<div></div>"
const template = document.createElement("template");
template.insertAdjacentHTML("afterbegin", "<div></div>")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
innerHTML | 154618.4 Ops/sec |
insertAdjacentHTML | 150956.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The benchmark is designed to compare two approaches for rendering HTML templates in a browser: innerHTML
and insertAdjacentHTML
. The benchmark uses the template
element, which is a Web Components API that allows creating and manipulating HTML templates.
Script Preparation Code
There is no script preparation code provided for this benchmark. This means that the JavaScript engine will create the template element and assign it to the template
variable without any additional setup or initialization code.
Html Preparation Code
Similarly, there is no html preparation code provided for this benchmark. The HTML code for the test case is hard-coded directly into the Benchmark Definition
JSON:
const template = document.createElement("template");
template.innerHTML = "<div></div>";
or
const template = document.createElement("template");
template.insertAdjacentHTML("afterbegin", "<div></div>");
Individual Test Cases
There are two test cases in this benchmark:
template
element and assigns an HTML string to its innerHTML
property.template
element, but instead of assigning an HTML string to its innerHTML
property, it uses the insertAdjacentHTML
method to insert an HTML fragment into the template.Library and Purpose
In this benchmark, the Web Components API (template
) is used to create and manipulate HTML templates. The template
element is a new addition to the Web Components API, introduced in Chrome 85 (released in March 2020).
Special JS Feature or Syntax
The benchmark uses the insertAdjacentHTML
method, which was introduced in ECMAScript 2019 (ES11). This method allows inserting HTML fragments into an element without the need for innerHTML
or other methods.
Pros and Cons of Different Approaches
innerHTML
, as it avoids parsing and sanitizing user-supplied HTML.Other Alternatives
Some other alternatives for rendering HTML templates in a browser include:
createElement
, appendChild
) to build and render the HTML template.However, Web Components API (template
) is a popular choice for building reusable UI components and templates due to its simplicity and flexibility.
Additional Considerations
When choosing an approach for rendering HTML templates in a browser, consider factors such as:
I hope this explanation helps you understand what's being tested in MeasureThat.net!