var a = document.createElement('a');
a.appendChild(document.createTextNode('text'));
a.textContent = 'text';
a.innerText = 'text';
a.append('text');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createTextNode | |
textContent | |
innerText | |
append |
Test name | Executions per second |
---|---|
createTextNode | 3953100.2 Ops/sec |
textContent | 8911574.0 Ops/sec |
innerText | 4716821.5 Ops/sec |
append | 4265972.5 Ops/sec |
Let's break down what's being tested in the provided benchmark.
Benchmark Overview
The benchmark compares four different approaches to appending or setting text content on an HTML element: createTextNode
, textContent
, innerText
, and append
. The test is run in a Firefox browser on a Windows desktop device.
Approaches Compared
createTextNode
: This method creates a new Text node object using the document.createTextNode()
method, which returns a node that represents plain text.textContent
: This method sets the text content of an element directly. It replaces any existing child nodes or text content with the specified value.innerText
: This method is not supported in older browsers, but it's available in modern versions like Firefox 130. It sets the inner text of an element, which includes HTML tags and attributes. In older browsers, textContent
would be used instead.append
: This method appends a string to the end of an element's contents.Pros and Cons
createTextNode
: Creates a new Text node object, which can be useful for precise control over text content. However, it requires creating a separate node, which might incur additional overhead.textContent
: Sets the text content directly, which is fast but may replace existing child nodes or text content. In some cases, this can lead to unnecessary reflows or layout recalculations.innerText
(modern browsers): Sets the inner text of an element, including HTML tags and attributes. This approach can be useful when you need to preserve the original structure, but it may not be supported in older browsers.append
: Appends a string to the end of an element's contents, which is simple and fast but might lead to unnecessary reflows or layout recalculations if not done carefully.Library Used
None explicitly mentioned. The benchmark only uses standard JavaScript APIs and DOM methods.
Special JS Feature/Syntax
There are no specific JavaScript features or syntaxes being tested in this benchmark. It focuses on comparing the performance of different text content manipulation approaches.
Other Alternatives
Alternative approaches to appending or setting text content include:
innerHTML
instead of textContent
(which can be faster but may lead to security issues if not sanitized)span
, and inserting it manually using the insertAdjacentHTML()
methodKeep in mind that these alternative approaches might have their own trade-offs in terms of performance, security, or convenience.