var a = document.createElement('a');
a.appendChild(document.createTextNode('text'));
a.textContent += 'text';
a.innerText += 'text';
a.innerHTML += 'text';
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createTextNode | |
textContent | |
innerText | |
innerHTML |
Test name | Executions per second |
---|---|
createTextNode | 1947529.8 Ops/sec |
textContent | 1.7 Ops/sec |
innerText | 1.4 Ops/sec |
innerHTML | 0.8 Ops/sec |
The benchmark defined in the provided JSON compares four methods of manipulating the DOM in JavaScript: createTextNode
, textContent
, innerText
, and innerHTML
. It aims to measure the performance of these methods in terms of how many executions can be performed per second on a mobile device running Chrome.
createTextNode
:
a.appendChild(document.createTextNode('text'));
a
.textContent
:
a.textContent += 'text';
a
. Using +=
appends to the existing text.innerText
:
a.innerText += 'text';
textContent
, this property retrieves or sets the visible text of a
while taking into account the CSS styles.textContent
as it requires layout recalculations to ensure the visibility of text, and may not accurately reflect HTML content.innerHTML
:
a.innerHTML += 'text';
From the benchmark results provided:
createTextNode
outperformed all other methods, with an impressive execution rate of approximately 1,039,538 executions per second.textContent
came next at around 33.15 executions per second, followed closely by innerText
at 26.95 executions per second.innerHTML
performed the worst, with only 1.78 executions per second, highlighting its inefficiency for simple text additions.Use Case: The choice of method largely depends on the specific requirements. If only text needs to be added, createTextNode
or textContent
would be preferable. If HTML structures are needed, innerHTML
is the option, despite its performance drawbacks.
Security: When dealing with user-generated content, always prefer textContent
or createTextNode
to avoid security issues associated with innerHTML
.
Cross-Browser Behavior: While these methods generally behave consistently across modern browsers, nuances can exist in older browsers or less common environments.
Some alternatives to consider when manipulating the DOM in modern web applications include: