<div id='dest'></div>
const dest = document.getElementById('dest');
function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
for(var i=0; i<1000; ++i){
dest.insertAdjacentHTML("beforeend", "<p></p>");
dest.lastChild.innerText = `Hello ${i} & hello again.`;
}
var html = "";
for(var i=0; i<1000; ++i){
html += `<p>${escapeHtml(`Hello ${i} & hello again.`)}</p>`;
}
dest.innerHTML = html;
for(var i=0; i<1000; ++i){
dest.insertAdjacentHTML("beforeend", "<p></p>");
dest.lastElementChild.innerText = `Hello ${i} & hello again.`;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
insertAdjacentHTML+innerText | |
escape+insertAdjacentHTML | |
insertAdjacentHTML+innerText w/ lastElementChild |
Test name | Executions per second |
---|---|
insertAdjacentHTML+innerText | 259.3 Ops/sec |
escape+insertAdjacentHTML | 605.9 Ops/sec |
insertAdjacentHTML+innerText w/ lastElementChild | 239.0 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Definition
The website MeasureThat.net provides a JSON representation of a JavaScript microbenchmark. In this case, we have three test cases:
insertAdjacentHTML+innerText
escape+insertAdjacentHTML
insertAdjacentHTML+innerText w/ lastElementChild
These test cases aim to measure the performance difference between using insertAdjacentHTML
with inner text (innerText
) and using HTML escaping (with escapeHtml
function) followed by insertAdjacentHTML
.
Options Compared
The options being compared are:
insertAdjacentHTML
with innerText
: This method appends a new HTML element to the end of an existing element, including its content.insertAdjacentHTML
with HTML escaping (using escapeHtml
function): This method also appends a new HTML element to the end of an existing element but uses HTML escaping to ensure the content is safe for display in an HTML document.Pros and Cons
insertAdjacentHTML
with innerText
:insertAdjacentHTML
with HTML escaping:escapeHtml
) to perform the escaping, adding complexity.Library and Purpose
The library used here is not explicitly mentioned, but it's likely that insertAdjacentHTML
is part of the HTML5 API. The purpose of this API is to provide a convenient way to append new elements or attributes to an existing element without affecting its structure.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax being tested in these benchmark cases. They focus on comparing different approaches for inserting content into an element using insertAdjacentHTML
.
Other Alternatives
If you're looking for alternatives to measure the performance of your code, you can consider:
Keep in mind that MeasureThat.net is specifically designed for comparing JavaScript microbenchmarks, so it might not be the best option for more complex performance evaluations.