Sub topic 10
Template Object Caching per Call Site
This chapter assumes you already know how tag functions receive the strings array and the values arguments, and that you know the strings.raw property. It also uses WeakMap, a map whose keys must be objects and are held weakly, so a cached entry can be garbage-collected once nothing else refers to its key.
A tagged template does not build a new strings array every time it runs. JavaScript creates one template object for each call site, which is each place in the source code where a tagged template is written. It then hands that same frozen object to the tag on every evaluation. Libraries use this to do expensive work once per template instead of once per call.
One Template Object per Call Site
The template object is the strings array together with its raw array. The engine creates it the first time a given call site is evaluated and stores it. Every later evaluation of that call site reuses the stored object, whatever values are interpolated.
function id(strings) {
return strings;
}
function greet(name) {
return id`Hello, ${name}!`;
}
const a = greet("Ada");
const b = greet("Bob");
console.log(a === b); // true: same call site
console.log(Object.isFrozen(a)); // true
console.log(Object.isFrozen(a.raw)); // true
const c = id`Hello, ${"Ada"}!`;
console.log(a === c); // false: different call site, same textThe ${name} value changes between calls, but strings never does. The values are passed separately as fresh arguments each time, and only the literal parts are cached.
The last comparison matters. Two call sites with identical text get different template objects. Early versions of the specification (ES2015 to ES2018) cached by the raw string content, so identical text shared one object. ES2019 changed the rule so the cache belongs to the source location. That change prevents unrelated code from sharing a cache entry and keeps the entries collectable.
Why the Arrays Are Frozen
Every evaluation of a call site shares one object, so a tag that changed it would corrupt every later call. Freezing rules that out. Writing to an index fails silently in sloppy mode and throws in strict mode. Methods that change the array, such as push, always throw.
"use strict";
function tryMutate(strings) {
try {
strings[0] = "changed";
} catch (e) {
console.log(e instanceof TypeError); // true
}
return strings[0];
}
console.log(tryMutate`original`); // originalUsing the Strings Array as a Cache Key
Templating libraries often parse the literal parts into an internal form, such as a compiled render plan or a DOM template. The strings array is stable for each call site and is an object, so it works as a WeakMap key.
const cache = new WeakMap();
let compileCount = 0;
function compile(strings) {
compileCount++;
// Stand-in for expensive parsing work.
return strings.map(s => s.toUpperCase());
}
function shout(strings, ...values) {
let parts = cache.get(strings);
if (!parts) {
parts = compile(strings);
cache.set(strings, parts);
}
return parts.reduce((out, s, i) => out + values[i - 1] + s);
}
function render(name) {
return shout`hello, ${name}!`;
}
console.log(render("Ada")); // HELLO, Ada!
console.log(render("Bob")); // HELLO, Bob!
console.log(compileCount); // 1
console.log(shout`hello, ${"Cy"}!`); // HELLO, Cy!
console.log(compileCount); // 2render runs twice but compiles once. The second shout call has the same text, but it sits at a new call site, so it gets its own entry. A WeakMap is the right container here. Once the code holding a call site is unreachable, its template object can be collected, and the cache entry goes with it.
What Counts as the Same Call Site
| Situation | Same template object? |
|---|---|
| Same tagged template evaluated in a loop | Yes |
| Same tagged template inside a function called many times | Yes |
| Same code inside closures created repeatedly | Yes, closures share source |
| Two separate tagged templates with identical text | No |
| Same text run through `eval` or `new Function` again | No, each parse is new source |
| Same code loaded in a different realm (iframe, worker) | No |
Exercise
A tag caches compiled output in a WeakMap keyed by strings. The code calls [1, 2, 3].map(n => tagitem ${n}) and then, on a later line, writes tagitem ${4}``. How many times does the compile step run, and why?
Show answer
Twice. The three calls inside map all evaluate the same call site, so they share one frozen template object and compile once. The later line is a separate call site, so it gets a different template object even though its text is identical, and that causes a second compile.
Exercise
Why does the specification freeze the template object instead of handing each call a fresh copy?
Show answer
The template object is created once per call site and reused on every evaluation. If it could be changed, a tag that edited it would alter the strings seen by all later calls from that site. Freezing makes sharing safe and keeps the object reliable as a cache key.