Sub topic 10
Frozen Strings Arrays and Call-Site Caching
This chapter assumes you know how a tag function receives strings and ...values, and that you are comfortable with Map, WeakMap, and closures. It covers two guarantees the engine makes about the strings array. The array cannot be changed, and the same array is passed every time a given call site runs.
The strings array is frozen
The engine freezes the strings array before passing it to your tag. It also freezes the strings.raw array attached to it. Static template text is part of your source code, so the engine treats it as read-only.
function grab(strings) {
return strings;
}
const s = grab`a${1}b`;
console.log(Object.isFrozen(s)); // true
console.log(Object.isFrozen(s.raw)); // true
function mutate(arr) {
'use strict';
arr[0] = 'changed';
}
try {
mutate(s);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(s[0]); // 'a'In sloppy mode the assignment fails silently. In strict mode, which includes all ES modules, it throws a TypeError. If your tag needs a modified copy, use [...strings] or strings.map(...) to make one.
One array per call site
A call site is one place in the source code where a tagged template appears. Every time that site runs, the engine passes the same strings object. This holds across loop iterations and across repeated calls to the enclosing function. A different site gets its own array, even when its text is character-for-character identical.
| Situation | Same `strings` object? |
|---|---|
| Same site, loop runs 100 times | Yes |
| Same site inside a function called repeatedly | Yes |
| Two sites with identical text | No |
| Same text evaluated again with `eval` or `new Function` | No, because the code is parsed again |
Using identity as a cache key
The static parts never change for a given site, so anything you compute from them alone can be computed once and reused. Libraries such as lit do this. They parse the template's markup the first time a site runs, then reuse the parsed result and only update the values.
const cache = new WeakMap();
let compiles = 0;
function compile(strings) {
compiles++;
return { markup: strings.join('{{}}'), slots: strings.length - 1 };
}
function render(strings, ...values) {
let compiled = cache.get(strings);
if (compiled === undefined) {
compiled = compile(strings);
cache.set(strings, compiled);
}
return { ...compiled, values };
}
const item = (n) => render`<li>${n}</li>`;
item(1);
item(2);
console.log(item(3)); // { markup: '<li>{{}}</li>', slots: 1, values: [ 3 ] }
console.log(compiles); // 1Common errors
- Caching on values. Only
stringsis stable. The values change on every call, so anything you derive from them must not go in the per-site cache. - Expecting identical text to share a cache entry. Two sites with the same text each miss the cache once. If you need them to share an entry, key on content such as
strings.raw.join('\u0000')and accept the cost of building that string on every call. - Mutating
stringsto "normalize" it. The array is frozen. Copy it first, or cache the normalized copy against the original array.
Exercise
A function greet(name) contains the template html<p>${name}</p>, and you call it 50 times. A second function contains the same template text and is called once. Using the WeakMap cache above, how many times does compile run, and why?
Show answer
Twice. The 50 calls all run the same call site, so they receive the same frozen strings array and hit the cache after the first call. The second function is a separate call site, so it gets a different array and misses the cache once, even though its text is identical.
Exercise
Inside an ES module, a tag runs strings.push('x'). What happens?
Show answer
It throws a TypeError. Modules are always strict mode, and the strings array is frozen, so it cannot be extended.