observablehq / htl

A tagged template literal that allows safe interpolation of values into HTML, following the HTML5 spec
https://observablehq.com/@observablehq/htl
ISC License
305 stars 24 forks source link

Improve performance by caching templates? #24

Open mbostock opened 3 years ago

mbostock commented 3 years ago

Modifying the renderHtml function (and likewise renderSvg) could greatly improve the performance of Hypertext Literal when rendering the same template over and over again. Something like:

const cache = new Map();

function renderHtml(string) {
  if (cache.has(string)) return cache.get(string).cloneNode(true);
  const template = document.createElement("template");
  template.innerHTML = string;
  const {content} = template;
  cache.set(string, content);
  return content;
}

But, open questions:

  1. When should the cache be cleared (e.g., after a requestAnimationFrame or Promise.resolve())? Should caching be optional or configurable? Should the size of the cache be? Should the cache be scoped to individual literals using a WeakMap?

  2. Hypertext Literal may currently inline interpolated values into the generated HTML to avoid needing to walk the tree and substitute dynamic values into placeholders (e.g., comments). However when caching, it might be desirable to always use placeholders, so that the generated template is never dependent on the interpolated values and can be shared.

I’d also love realistic benchmarks that we can use to measure these potential performance improvements.