<div id='hello'>Hello, World!</div>
let el = document.querySelector("#hello");
let i = 1000;
let el = document.querySelector("#hello");
while (i--) {
el.innerText = "Goodbye, cruel world!"
}
let i = 1000;
let el = document.querySelector("#hello");
while (i--) {
el.innerHtml = "Goodbye, cruel world!"
}
var g_DOMParser = new DOMParser();
function decodeHTMLSymbols(htmlText) {
return g_DOMParser.parseFromString(htmlText, "text/html").documentElement.textContent;
}
let i = 1000;
let el = document.querySelector("#hello");
while (i--) {
if (el.innerHTML != decodeHTMLSymbols("Goodbye, cruel world!"))
{
el.innerHtml = "Goodbye, cruel world!"
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerText | |
innerHtml | |
innerText with Compare |
Test name | Executions per second |
---|---|
innerText | 382.6 Ops/sec |
innerHtml | 519536.8 Ops/sec |
innerText with Compare | 24.0 Ops/sec |
Let's dive into the world of JavaScript benchmarks.
Benchmark Definition
The benchmark measures the performance of three approaches to update the text content of an HTML element:
innerHTML
: Setting the innerHTML
property directly on the element.innerText
: Using the innerText
property (available in modern browsers) or equivalent methods like textContent
and innerHTML
that only set the text content without modifying the DOM structure.Options Compared
The benchmark compares the performance of these three approaches:
innerHTML
: Simple and straightforward, but can lead to DOM pollution if not used carefully. Can be slower due to the need to reparse the entire DOM.innerText
: Modern browsers support this property, which is generally faster than innerHTML
. However, older browsers may not support it.DOMParser
API to implement the custom approach, which is a relatively modern feature. This might limit its compatibility with older browsers.Library Used
In the "custom" test case, the DOMParser
library is used to parse HTML symbols. Specifically, it's used to decode HTML entities and preserve the original formatting of the input text.
Special JS Feature/Syntax
The benchmark uses modern JavaScript features like arrow functions (=>
) and template literals (``). These are not specific to any particular browser or version, but can affect code readability and compatibility with older browsers.
Benchmark Result
The latest benchmark results show that:
innerHTML
is the slowest approach.innerText
is faster than innerHTML
, but slower than the custom implementation.These results are likely influenced by factors like browser version, platform, and hardware capabilities. However, they provide a general idea of how these approaches compare in terms of performance.