Skip to content

Commit 00a7bd0

Browse files
Frontend/perf: Cache Intl.DateTimeFormat objects. (#8122)
1 parent 2562748 commit 00a7bd0

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

app/web/utils/date.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,29 @@ export function localizeDateTimeRange(
6666
return format.formatRange(start, end);
6767
}
6868

69-
/// gets in an Intl.DateTimeFormat based on params.
69+
// Creating Intl.DateTimeFormat every time is 40x slower.
70+
const intlDateTimeFormatCache = new Map<string, Intl.DateTimeFormat>();
71+
72+
/// Gets an Intl.DateTimeFormat based on params.
7073
function getIntlDateTimeFormat(
7174
args: LocalizeDateTimeParams,
75+
): Intl.DateTimeFormat {
76+
// We can't use args as the Map key as it uses reference equality.
77+
// Convert it to a json string. The Symbol type requires special handling.
78+
const cacheKey = JSON.stringify(args, (_, v) =>
79+
typeof v === "symbol" ? v.toString() : v,
80+
);
81+
const cached = intlDateTimeFormatCache.get(cacheKey);
82+
if (cached) return cached;
83+
84+
const format = createIntlDateTimeFormat(args);
85+
intlDateTimeFormatCache.set(cacheKey, format);
86+
return format;
87+
}
88+
89+
/// Creates a new Intl.DateTimeFormat object based on params.
90+
function createIntlDateTimeFormat(
91+
args: LocalizeDateTimeParams,
7292
): Intl.DateTimeFormat {
7393
const options: Intl.DateTimeFormatOptions = {};
7494
if (args.includeDate !== false) {

0 commit comments

Comments
 (0)