<template></template>
<div id="T1"></div>
<div id="T2"></div>
<div id="T3"></div>
<div id="T4"></div>
<div id="T5"></div>
// Needs var hoisting, can't use let or const declarations!
var htmlTemplate = document.querySelector("template");
var myHTML = `<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>`;
htmlTemplate.innerHTML = myHTML;
var globalTemplate = document.createElement("template");
globalTemplate.innerHTML = myHTML;
var clonedTemplate = globalTemplate.content.cloneNode(true);
document.querySelector("#T1").innerHTML = myHTML;
document.querySelector("#T2").appendChild(globalTemplate.content.cloneNode(true));
document.querySelector("#T3").append(globalTemplate.content.cloneNode(true));
document.querySelector("#T4").append(htmlTemplate.content.cloneNode(true));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
T1 - set innerHTML | |
T2 - clone template - appendChild | |
T3 - clone Template - append | |
T4 - clone HTML Template |
Test name | Executions per second |
---|---|
T1 - set innerHTML | 43822.3 Ops/sec |
T2 - clone template - appendChild | 52595.3 Ops/sec |
T3 - clone Template - append | 26.5 Ops/sec |
T4 - clone HTML Template | 27.1 Ops/sec |
Let's break down the provided JSON data to explain what is tested, compared options, and other considerations.
Benchmark Definition
The benchmark measures the performance of three different approaches when cloning and appending HTML content in Web Components using JavaScript:
innerHTML
: Setting the innerHTML of a DOM element.appendChild
followed by cloneNode(true)
: Appending the cloned content to a DOM element and then cloning the new child node.append
followed by cloneNode(true)
: Directly appending the cloned content to a DOM element.Library and Syntax
The benchmark uses the following library:
document.querySelector
, innerHTML
, appendChild
, etc.).Some special JS features or syntax used in this benchmark include:
myHTML =
...`).cloneNode(true)
method to clone templates.Pros and Cons
Here are some pros and cons for each approach:
innerHTML
, as it avoids creating unnecessary DOM nodes.Other Considerations
When choosing between these approaches, consider the following factors:
appendChild + cloneNode(true)
or append + cloneNode(true)
might be better choices.innerHTML
might be a better option, despite potential performance drawbacks.Alternatives
If you're looking for alternative approaches or variations on these methods, consider:
createElement
followed by appendChild
and then cloning.In conclusion, the benchmark provides a fair comparison of three different approaches to cloning and appending HTML content in Web Components. By understanding the pros and cons of each method, developers can make informed decisions about which approach best suits their needs, considering factors like performance, complexity, and personal preference.