const count = 20_000;
const testString = '<div>' + (new Array(count)).fill('').join('<b>x</b>') + '</div>';
function test_createHTMLDocument() {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = testString;
return doc.body;
}
function test_DOMParser() {
return (new DOMParser()).parseFromString(testString, 'text/html').body;
}
function test_documentFragment() {
return document.createRange().createContextualFragment(testString);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.createHTMLDocument() + .innerHTML | |
DOMParser | |
Nested .createElement() + .appendChild() |
Test name | Executions per second |
---|---|
.createHTMLDocument() + .innerHTML | 226807072.0 Ops/sec |
DOMParser | 218004352.0 Ops/sec |
Nested .createElement() + .appendChild() | 213679568.0 Ops/sec |
In this benchmark, three different methods for generating HTML content within a JavaScript environment are compared. The methods tested are:
.createHTMLDocument()
combined with .innerHTML
DOMParser
createContextualFragment()
from document.createRange()
.createHTMLDocument()
+ .innerHTML
:
innerHTML
property of the body.DOMParser
:
innerHTML
, especially for very large HTML strings.createContextualFragment()
:
DocumentFragment
from a string of HTML, which can then be appended to the DOM. This method is part of the Range
interface.DocumentFragment
is a lightweight container, which allows for batch DOM manipulations and is generally more efficient for appending multiple nodes..createHTMLDocument()
, making it beneficial for performance particularly in more extensive manipulations.innerHTML
directly, particularly for complex HTML structures.While these three methods are compared in this benchmark, developers have various alternatives available depending on their needs:
Direct DOM Manipulation: Using methods like .createElement()
, .appendChild()
, and others to build elements would generally be the most flexible, though it might require more code compared to the other options.
Template Literals: For cases where you need to create HTML with interpolation, ES6 template literals could be used along with .innerHTML
, although this method carries the same risks associated with innerHTML
.
Frontend Frameworks: Libraries and frameworks like React, Angular, or Vue.js have their own systems for managing DOM updates that are highly optimized and provide better management compared to the direct manipulation of the DOM.
When choosing between these methods, performance, ease of use, security, and the specific application requirements should guide the decision. The benchmark results indicate relative performance among these methods, suggesting that .createHTMLDocument()
yields the highest number of executions per second in this context, followed closely by DOMParser
, and then createContextualFragment()
.