Template element vs string literal

JavaScript performance comparison

Test case created by terodox

Preparation code

<template>
  <style>
   h1 {
     color: red;
     font-family: Arial, sans-serif;
     font-weight: 500;
   }
   p {
     color: green;
     font-family: Helvetica, sans-serif;
     font-weight: 300;
   }
  </style>
  <h1>Replaced at render time<h1>
  <p>This is a general paragraph to demonstrate more than a single tag, because.... SCIENCE!</p>
</template>
      
<script>
Benchmark.prototype.setup = function() {
  if(!window.init) {
  class TemplatedCode extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        const template = document.querySelector('template');
        const clone = document.importNode(template.content, true);
        clone.querySelector('h1').innerText = 'Updating the title!';
        this.shadowRoot.appendChild(clone);
    }
  }
  customElements.define('template-code', TemplatedCode);
  
  class StringLiteralCode extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        const title = 'Updating the title!';
        this.shadowRoot.innerHTML = `
          <style>
              h1 {
                  color: red;
                  font-family: Arial, sans-serif;
                  font-weight: 500;
              }
              p {
                  color: green;
                  font-family: Helvetica, sans-serif;
                  font-weight: 300;
              }
          </style>
          <h1>${title}<h1>
          <p>This is a general paragraph to demonstrate more than a single tag, because.... SCIENCE!</p>
        `;
    }
  }
  customElements.define('string-literal-code', StringLiteralCode);
  
  window.init = true;
  }

};
</script>

Preparation code output

<template> <style> h1 { color: red; font-family: Arial, sans-serif; font-weight: 500; } p { color: green; font-family: Helvetica, sans-serif; font-weight: 300; } </style> <h1>Replaced at render time<h1> <p>This is a general paragraph to demonstrate more than a single tag, because.... SCIENCE!</p> </template>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Create with templated element
document.body.appendChild(document.createElement('template-code'));
pending…
Create with string literal
document.body.appendChild(document.createElement('string-literal-code'));
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 Comments