<html>
<body>
<div id='test'>Hello, World</div>
</body>
</html>
var parent = document.getElementById('test');
var setTextContent1 = Object.getOwnPropertyDescriptor(Node.prototype, 'textContent').set;
var nodeFirstChild = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild').get;
var nodeLastChild = Object.getOwnPropertyDescriptor(Node.prototype, 'lastChild').get;
var setTextContent2 = (node, text) => {
if (text) {
const firstChild = nodeFirstChild.call(node);
if (
firstChild && firstChild.nodeType === 3 /** TEXT_NODE */ && firstChild === nodeLastChild.call(node)
) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
}
parent.textContent = 'Hello, Sukka';
setTextContent1.call(parent, 'Hello, Million');
setTextContent2(parent, 'Hello, Performance');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set textContent | |
cached textContent prototype | |
avoid remove the existing node and create a new one |
Test name | Executions per second |
---|---|
set textContent | 257065.0 Ops/sec |
cached textContent prototype | 298750.3 Ops/sec |
avoid remove the existing node and create a new one | 3603459.5 Ops/sec |
The provided JSON represents a JavaScript microbenchmarking test suite created on the MeasureThat.net website. The benchmark tests three different approaches to set the text content of an HTML element.
Approaches compared:
textContent
property of the HTML element to set its text content.textContent
property by calling the getter method (get
) on the Node.prototype
object and storing it in a variable. Then, when setting the text content, it calls this cached function instead of directly accessing the textContent
property.setTextContent2
) that checks if the existing child node is still present before updating its value.Pros and Cons:
textContent
property is used in a custom way).Library/Custom Function:
The setTextContent2
function uses a custom implementation that checks if the existing child node is still present before updating its value. It's essential to note that this approach may not work in all scenarios, especially when dealing with complex DOM structures or edge cases.
JavaScript feature/Syntax:
There are no special JavaScript features or syntax used in these approaches. They rely on standard ECMAScript and DOM APIs.
Other alternatives:
If you need more control over the text content setting process, you could consider using other approaches, such as:
Keep in mind that the best approach will depend on the specific use case and performance requirements. MeasureThat.net's benchmark results can provide valuable insights to help you choose the most suitable method for your application.