var str = `<div>${Math.random().toString().slice(2)}</div>`;
var range = document.createRange();
var temp = document.createElement('template')
var res = '';
for(i=0; i<30000; i++){
res += str
}
var test1 = range.createContextualFragment(res)
temp.innerHTML = res
var test2 = temp.content
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createContextualFragment | |
innerHTML |
Test name | Executions per second |
---|---|
createContextualFragment | 107.3 Ops/sec |
innerHTML | 88.0 Ops/sec |
Let's break down the benchmark and its test cases.
What is being tested?
The provided JSON represents two microbenchmarks, each testing different approaches to create a contextual fragment in JavaScript.
createContextualFragment
: This approach uses the document.createRange()
method in conjunction with document.createElement('template')
to create a contextual fragment.innerHTML
: This approach uses the innerHTML
property of an element to assign a string value, which will automatically insert new nodes into the element's content.Options being compared
The two options being compared are:
createContextualFragment()
with a templateinnerHTML
with a string assignmentPros and Cons of each approach
createContextualFragment()
Pros:
Cons:
innerHTML
Pros:
Cons:
createContextualFragment()
due to the overhead of inserting new nodes into the DOM.createContextualFragment()
.Library used
In this benchmark, the template
element is used. The purpose of a template
element is to allow for incremental insertion of HTML content without the need to create a new document fragment each time. When assigned an innerHTML value, the template's content is inserted into the DOM in a single operation.
Special JavaScript feature or syntax
The benchmark uses the Math.random().toString().slice(2)
function to generate random strings for testing purposes. This function generates a string representation of a random number between 0 and 1, excluding the decimal point. The slice(2)
method is then used to extract the numeric part of the string.
Other alternatives
Alternative approaches to creating contextual fragments or inserting HTML content into the DOM include:
DOMParser
to parse an HTML string and insert it into the DOM.html()
function to set the innerHTML propertyKeep in mind that each of these alternatives may have different performance characteristics, trade-offs, and use cases compared to createContextualFragment()
or innerHTML
.