Sub topic 16
Reusing Formatters for Performance
This chapter assumes you know how to build an Intl.DateTimeFormat with a locale and options, as covered in the earlier chapters. You should also be comfortable running a script in Node.js or a browser console.
Why construction is the expensive part
When you call new Intl.DateTimeFormat(locale, options), the engine does real work. It negotiates the locale against the data it has, fills in default options, loads the calendar and pattern data, and resolves the time zone. Calling format() on the finished object only applies that prepared pattern to a single time value.
If code builds a new formatter for every row in a table, it repeats the setup work thousands of times and gets the same result each time. Building one formatter and reusing it pays that setup cost only once.
Measuring the difference
Run this script in Node.js 16 or later, or in a browser console:
const base = Date.UTC(2024, 0, 1);
const dates = Array.from({ length: 20000 }, (_, i) => new Date(base + i * 3600000));
const options = { dateStyle: "medium", timeZone: "UTC" };
let t0 = performance.now();
for (const d of dates) new Intl.DateTimeFormat("en-US", options).format(d);
let t1 = performance.now();
console.log(`new formatter per call: ${(t1 - t0).toFixed(1)} ms`);
const shared = new Intl.DateTimeFormat("en-US", options);
t0 = performance.now();
for (const d of dates) shared.format(d);
t1 = performance.now();
console.log(`shared formatter: ${(t1 - t0).toFixed(1)} ms`);The exact timings depend on the engine and the machine. In most runtimes the shared formatter is many times faster. The toLocaleDateString and toLocaleString shortcuts take locale and options arguments, so they may build a formatter internally on each call. Some engines cache the result and some do not, so don't count on it in hot loops.
A small formatter cache
Sometimes the locale or options are only known at runtime, for example when each user has their own locale. In that case, cache formatters by a key built from the locale and the options:
const cache = new Map();
function getDateFormatter(locale, options = {}) {
const key = `${locale}|${JSON.stringify(options)}`;
let fmt = cache.get(key);
if (!fmt) {
fmt = new Intl.DateTimeFormat(locale, options);
cache.set(key, fmt);
}
return fmt;
}
const opts = { dateStyle: "long", timeZone: "UTC" };
const when = new Date(Date.UTC(2024, 6, 4));
console.log(getDateFormatter("en-US", opts).format(when)); // "July 4, 2024"
console.log(getDateFormatter("en-US", opts) === getDateFormatter("en-US", opts)); // true
console.log(cache.size); // 1Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Building a formatter inside `map` or a render function | Slow lists and slow renders | Hoist it to module scope or cache it |
| Calling `toLocaleString(locale, options)` in a loop | Possible construction on every call | Use one shared `Intl.DateTimeFormat` |
| Cache with no limit and unbounded keys | Memory grows over time | Keep the set of keys small and known |
Exercise
A React component renders 500 rows and calls row.date.toLocaleDateString(user.locale, { dateStyle: "medium" }) for each row on every render. Rewrite the formatting so that construction happens at most once per distinct locale.
Show answer
Define the options once, for example const MEDIUM = { dateStyle: "medium" };, outside the component. Then format each row with getDateFormatter(user.locale, MEDIUM).format(row.date), using the caching function from this chapter. Because the options object is a module-level constant, its key is stable. The cache then builds one formatter per locale, and every later row and render reuses it.