Sub topic 16
Reusing Formatters for Performance
This chapter assumes you can already build an Intl.DateTimeFormat with dateStyle, timeStyle, and timeZone, and that you know the toLocale* shortcuts from earlier chapters. You should also be comfortable with Map and closures. It explains why creating a formatter costs more than using one, and gives patterns for sharing formatter instances without introducing stale or incorrect output.
Why Construction Is the Expensive Step
Calling new Intl.DateTimeFormat(locale, options) does a lot of setup work before any formatting happens:
- Locale negotiation. The engine compares the requested BCP 47 tags with the locales it supports and picks the best match.
- Option resolution. It validates every option, fills in defaults, and looks up the calendar, numbering system, and hour cycle.
- Time zone lookup. If you pass
timeZone, the engine canonicalizes the IANA name and loads its rules. If you don't, it reads the runtime's default zone. - Pattern building. It loads locale data from CLDR (the Unicode Common Locale Data Repository) and compiles a pattern such as
MMM d, y.
After that setup, format(date) only fills the compiled pattern with numbers from the time value. That is why the first call is slow and later calls are cheap. Intl.NumberFormat, Intl.RelativeTimeFormat, and Intl.PluralRules follow the same model.
Measuring the Difference
The script below runs in Node.js 16 or later and in any modern browser console, because both provide performance.now() as a global. The exact numbers depend on your engine and machine. The ratio between the two loops is the useful result.
const dates = Array.from({ length: 20000 }, (_, i) => new Date(Date.UTC(2024, 0, 1) + i * 3600000));
const options = { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" };
let t0 = performance.now();
for (const d of dates) {
new Intl.DateTimeFormat("en-US", options).format(d); // new formatter every time
}
const perCall = performance.now() - t0;
const shared = new Intl.DateTimeFormat("en-US", options);
t0 = performance.now();
for (const d of dates) {
shared.format(d); // one formatter, reused
}
const reused = performance.now() - t0;
console.log(`new each call: ${perCall.toFixed(1)} ms`);
console.log(`reused: ${reused.toFixed(1)} ms`);
console.log(`ratio: ${(perCall / reused).toFixed(1)}x`);On typical V8 builds the reused loop runs well over ten times faster. The exact ratio varies, but the reused loop is consistently faster.
Pattern 1: A Module-Level Constant
When the locale and options are fixed, create the formatter once at module scope:
const shortDate = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" });
function renderRows(rows) {
return rows.map((row) => `${row.name}: ${shortDate.format(row.createdAt)}`);
}
console.log(renderRows([{ name: "A", createdAt: new Date(Date.UTC(2024, 0, 15)) }]));
// [ 'A: Jan 15, 2024' ]This is the simplest pattern and the right default. Formatters hold no per-call state, so a single instance can serve the whole program.
Pattern 2: A Keyed Cache
When locale or options are chosen at runtime, for example from a user's settings, cache one formatter per distinct combination:
const dtfCache = new Map();
function getDateTimeFormat(locale, options = {}) {
// Sort keys so { a, b } and { b, a } produce the same cache key.
const key = locale + "|" + JSON.stringify(options, Object.keys(options).sort());
let fmt = dtfCache.get(key);
if (!fmt) {
fmt = new Intl.DateTimeFormat(locale, options);
dtfCache.set(key, fmt);
}
return fmt;
}
const d = new Date(Date.UTC(2024, 6, 4, 16, 30));
const a = getDateTimeFormat("de-DE", { timeZone: "Europe/Berlin", dateStyle: "short" });
const b = getDateTimeFormat("de-DE", { dateStyle: "short", timeZone: "Europe/Berlin" });
console.log(a === b); // true: same formatter despite different key order
console.log(a.format(d)); // "04.07.24"
console.log(dtfCache.size); // 1Passing an array as the second argument of JSON.stringify makes it a whitelist, and the output follows the array's order. Sorting the keys therefore gives a stable key. This works because Intl options are flat objects. Nested values would need a deeper normalization.
Gotchas When Sharing Formatters
The default time zone is captured at construction
A formatter created without timeZone saves the runtime's zone when it is built. If that zone changes later, for example a Node.js test that sets process.env.TZ, or a laptop that moves between zones while a long-lived browser tab stays open, the cached formatter keeps using the old zone.
const fmt = new Intl.DateTimeFormat("en-US", { timeStyle: "short" });
console.log(fmt.resolvedOptions().timeZone); // zone at construction time, e.g. "Europe/Berlin"
// Even if the runtime's zone changes afterwards, fmt keeps reporting and using that zone.If correctness depends on the current zone, pass timeZone explicitly and include it in the cache key, or clear the cache when you detect a change.
Locale changes need invalidation
If your app lets users switch language without reloading, module-level constants built from the old locale keep producing old output. A keyed cache handles this naturally because the locale is part of the key. Module constants need to be rebuilt.
Unbounded caches can grow
If locale or option values come from untrusted input, such as a query parameter, an attacker can create a new cache entry with every request. Restrict inputs to a known list, or cap the cache size:
const MAX_ENTRIES = 100;
function remember(cache, key, create) {
if (cache.has(key)) return cache.get(key);
if (cache.size >= MAX_ENTRIES) {
cache.delete(cache.keys().next().value); // evict the oldest insertion
}
const value = create();
cache.set(key, value);
return value;
}
const nfCache = new Map();
const eur = remember(nfCache, "de-DE|EUR", () =>
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" })
);
console.log(eur.format(1234.5)); // e.g. "1.234,50 €"A Map iterates in insertion order, so deleting the first key evicts the oldest entry. Re-inserting a key on each hit would turn this into a least-recently-used cache.
Which `format` methods are pre-bound
Intl.DateTimeFormat.prototype.format and Intl.NumberFormat.prototype.format are getters that return a function already bound to the instance. You can pass them directly as callbacks. Intl.RelativeTimeFormat and Intl.PluralRules methods are ordinary methods, so passing them without the instance loses this.
const dtf = new Intl.DateTimeFormat("en-US", { month: "short", timeZone: "UTC" });
const months = [0, 1, 2].map((m) => new Date(Date.UTC(2024, m, 1)));
console.log(months.map(dtf.format)); // [ 'Jan', 'Feb', 'Mar' ]: works, format is bound
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const fmtDays = (n) => rtf.format(n, "day"); // wrap it; rtf.format alone is unbound
console.log([-1, 0, 1].map(fmtDays)); // [ 'yesterday', 'today', 'tomorrow' ]When Reuse Doesn't Matter
Formatting a single timestamp in a page header doesn't need a cache. Reuse matters in hot paths: table rows, chart axis labels, log processing, server-side rendering of long lists, and UI components that re-render on every keystroke. Profile first. If Intl constructors appear in the flame graph, hoist or cache them.
| Situation | Recommended approach |
|---|---|
| Fixed locale and options | Module-level constant |
| Locale or options from user settings | Keyed `Map` cache |
| Inputs from untrusted sources | Allow-list or size-capped cache |
| Zone-sensitive output in long-lived processes | Explicit `timeZone` in options and key |
| One-off formatting | `toLocale*` shortcut is fine |
Exercise
A React component calls date.toLocaleDateString(locale, { dateStyle: "long" }) for each of 5,000 table rows on every render. Describe a fix and explain why it is faster.
Show answer
Build the formatter once per locale, either with a module-level constant or with a keyed cache such as getDateTimeFormat(locale, { dateStyle: "long" }), and call fmt.format(date) for each row. toLocaleDateString with options behaves as if it constructs a new Intl.DateTimeFormat per call, which repeats locale negotiation, option resolution, and pattern compilation 5,000 times. A shared formatter runs that setup once and only fills in the pattern for each row.
Exercise
Why does [-2, -1].map(rtf.format) fail for an Intl.RelativeTimeFormat instance rtf, while dates.map(dtf.format) works for an Intl.DateTimeFormat instance dtf? Even if it were bound, what other problem would the first call have?
Show answer
DateTimeFormat's format is a getter that returns a function bound to its instance. RelativeTimeFormat's format is an ordinary prototype method, so passing it to map loses this and throws a TypeError. Even if it were bound, map would pass the array index as the second argument, so the unit would be a number instead of a string like "day", and that also throws. Wrap it instead: (n) => rtf.format(n, "day").
Exercise
A Node.js test suite caches new Intl.DateTimeFormat("en-US", { timeStyle: "short" }) in a module, then sets process.env.TZ to different zones between tests. The output never changes. Why, and how should the cache be fixed?
Show answer
A formatter built without a timeZone option saves the runtime's default zone at construction time, so the cached instance keeps the zone it saw first. Pass timeZone explicitly and include it in the cache key, or rebuild or clear the cache whenever the zone changes.