var a = document.createElement('a');
a.appendChild(document.createTextNode('text'));
a.textContent = 'text';
a.innerText = 'text';
a.append('text');
a.appendChild(new Text('text'));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createTextNode | |
textContent | |
innerText | |
append | |
new text |
Test name | Executions per second |
---|---|
createTextNode | 2633878.0 Ops/sec |
textContent | 4010845.0 Ops/sec |
innerText | 2354223.8 Ops/sec |
append | 4411581.0 Ops/sec |
new text | 3411447.5 Ops/sec |
Benchmark Overview
The provided benchmark compares the performance of six different approaches to set and retrieve text content on an HTML element: createTextNode
, textContent
, innerText
, append
, new Text
, and appendChild
. The goal is to determine which approach is fastest, most efficient, and reliable.
Options Compared
createTextNode
: Creates a new text node using the document.createTextNode()
method.textContent
: Sets the text content of an element using the element.textContent
property.innerText
: Sets the inner text of an element using the element.innerText
property (available in HTML5).append
: Appends a string to the end of an element's content using the element.append()
method (not a standard DOM method, but rather a custom implementation).new Text
: Creates a new text node using the Text
constructor.appendChild
: Appends a child node to an element using the element.appendChild()
method.Pros and Cons
createTextNode
:textContent
:innerText
:textContent
, but with better support for HTML5 elements.append
:new Text
:appendChild
:Library Usage
The new Text
method uses the Text
constructor, which is a built-in JavaScript class. The purpose of this library is to provide a way to create a new text node with custom attributes and behavior.
Special JS Features or Syntax
None mentioned in the provided benchmark definition.
Other Alternatives
Other approaches to set and retrieve text content include:
innerHTML
: Sets the HTML content of an element using the element.innerHTML
property. However, this method is not recommended due to security concerns (e.g., potential XSS attacks).createElementText
: A proprietary method used by some older browsers or environments to create a new text node.Keep in mind that these alternatives may have different performance characteristics, pros and cons, and are not recommended for use in modern web development.