Skip to content

Build your personal knowledge base with Trilium Notes

perf(client): memoize the Intl date formatters

Elian Dorana873dc69149d
diff --git a/apps/client/src/utils/formatters.bench.ts b/apps/client/src/utils/formatters.bench.ts
new file mode 100644
index 0000000000..0887c80c78
--- /dev/null
+++ b/apps/client/src/utils/formatters.bench.ts
@@ -0,0 +1,102 @@
+/**
+ * Guards the formatter memoization in `formatters.ts` against regressing.
+ *
+ * These helpers used to build a fresh `Intl.DateTimeFormat` on every call, which is invisible when a
+ * dialog formats one date and dominant when a collection view formats one per row: a 949-card board
+ * redraw runs `formatDateTime` once per dated promoted label on every card, and cost 158ms doing it.
+ * Memoizing the formatters took that to ~5ms.
+ *
+ * Each pair below measures a `formatters.ts` entry point against a bare cached `Intl.DateTimeFormat`
+ * doing the same job -- the floor. While the memo holds, the two run within ~1.3x of each other; the
+ * remainder is the locale lookup, date parsing and cache key that the floor skips. A pair blowing
+ * out to a 20-30x gap again means a construction has crept back into that path.
+ *
+ * ```
+ * pnpm --filter client exec vitest bench --run src/utils/formatters.bench.ts
+ * ```
+ */
+
+// formatters.ts pulls in i18n at module scope; i18next is not initialised in a bench run, and the
+// paths measured here never reach t() anyway.
+vi.mock("../services/i18n", async () => {
+ const { LOCALES } = await import("@triliumnext/commons");
+ return {
+ t: (key: string) => key,
+ getLocaleById: (id: string | null | undefined) => LOCALES.find((l) => l.id === id) ?? null
+ };
+});
+
+import { bench, describe, vi } from "vitest";
+
+import options from "../services/options";
+import { formatDateNumeric, formatDateTime } from "./formatters";
+
+const LOCALE = "en-GB";
+const DATE = new Date("2026-02-11T14:23:45Z");
+
+/** Cards on the board that surfaced this; each one formats at least one date per redraw. */
+const BOARD_CARDS = 949;
+
+options.set("formattingLocale", LOCALE);
+
+const formatterCache = new Map<string, Intl.DateTimeFormat>();
+
+describe("formatDateTime — date and time", () => {
+ bench("formatters.ts", () => {
+ formatDateTime(DATE, "short", "short");
+ });
+
+ bench("floor: bare cached Intl.DateTimeFormat", () => {
+ cachedFormatter(`${LOCALE}|short|short`, { dateStyle: "short", timeStyle: "short" }).format(DATE);
+ });
+});
+
+describe("formatDateTime — date only", () => {
+ bench("formatters.ts", () => {
+ formatDateTime(DATE, "short", "none");
+ });
+
+ bench("floor: bare cached Intl.DateTimeFormat", () => {
+ cachedFormatter(`${LOCALE}|short|none`, { dateStyle: "short" }).format(DATE);
+ });
+});
+
+describe("formatDateNumeric — with time (also probes the locale's hour cycle)", () => {
+ bench("formatters.ts", () => {
+ formatDateNumeric(DATE, true);
+ });
+
+ bench("floor: bare cached Intl.DateTimeFormat", () => {
+ cachedFormatter(`${LOCALE}|numeric|withTime`, {
+ year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit"
+ }).format(DATE);
+ });
+});
+
+describe(`board redraw — ${BOARD_CARDS} cards, one dated label each`, () => {
+ bench("formatters.ts", () => {
+ for (let i = 0; i < BOARD_CARDS; i++) {
+ formatDateTime(DATE, "short", "short");
+ }
+ });
+
+ bench("floor: bare cached Intl.DateTimeFormat", () => {
+ for (let i = 0; i < BOARD_CARDS; i++) {
+ cachedFormatter(`${LOCALE}|short|short`, { dateStyle: "short", timeStyle: "short" }).format(DATE);
+ }
+ });
+});
+
+/**
+ * The floor to measure against: the same map-keyed-on-arguments caching `formatters.ts` now does,
+ * with none of the locale resolution, date parsing or fallback handling around it.
+ */
+function cachedFormatter(key: string, formatOptions: Intl.DateTimeFormatOptions) {
+ let formatter = formatterCache.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(LOCALE, formatOptions);
+ formatterCache.set(key, formatter);
+ }
+
+ return formatter;
+}
diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.ts
index 77b7ee0f5f..655d47124f 100644
--- a/apps/client/src/utils/formatters.spec.ts
+++ b/apps/client/src/utils/formatters.spec.ts
@@ -102,6 +102,29 @@ describe("formatters", () => {
expect(() => formatDateTime(new Date(), "none", "none")).toThrow("Incorrect state.");
});
+ it("follows a locale change rather than reusing the formatter memoized for the previous one", () => {
+ // Formatters are cached to keep collection views from rebuilding one per row. The cache is
+ // keyed on locale as well as style precisely so this keeps working: keyed on style alone, it
+ // would go on rendering the first locale's pattern after the setting changed.
+ const date = new Date(Date.UTC(2026, 0, 25, 13, 30));
+
+ options.set("formattingLocale", "en-US");
+ const american = formatDateTime(date, "short", "none");
+
+ options.set("formattingLocale", "de");
+ const german = formatDateTime(date, "short", "none");
+
+ // Compared against a formatter built on the spot, so the assertion tracks whatever patterns
+ // the environment's ICU actually carries.
+ expect(american).toBe(new Intl.DateTimeFormat("en-US", { dateStyle: "short" }).format(date));
+ expect(german).toBe(new Intl.DateTimeFormat("de", { dateStyle: "short" }).format(date));
+ expect(german).not.toBe(american);
+
+ // Back again: the first entry has to still be right, not overwritten by the second locale.
+ options.set("formattingLocale", "en-US");
+ expect(formatDateTime(date, "short", "none")).toBe(american);
+ });
+
describe("formatDateNumeric", () => {
// Every locale the user can actually pick as a formatting locale, which is the set that
// declares an electronLocale (see the options page).
diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.ts
index d4d7d2c7a1..2bf3ecde78 100644
--- a/apps/client/src/utils/formatters.ts
+++ b/apps/client/src/utils/formatters.ts
@@ -59,27 +59,14 @@ export function formatDateTime(date: string | Date | number | null | undefined,
if (timeStyle !== "none" && dateStyle !== "none") {
// Format the date and time
- try {
- const formatter = new Intl.DateTimeFormat(locale, { dateStyle, timeStyle });
- return formatter.format(parsedDate);
- } catch (e) {
- const formatter = new Intl.DateTimeFormat(undefined, { dateStyle, timeStyle });
- return formatter.format(parsedDate);
- }
+ return getDateTimeFormatter(locale, `${dateStyle}-${timeStyle}`, { dateStyle, timeStyle }).format(parsedDate);
} else if (timeStyle === "none" && dateStyle !== "none") {
- // Format only the date
- try {
- return parsedDate.toLocaleDateString(locale, { dateStyle });
- } catch (e) {
- return parsedDate.toLocaleDateString(undefined, { dateStyle });
- }
+ // Format only the date. Equivalent to parsedDate.toLocaleDateString(locale, { dateStyle }):
+ // an explicit dateStyle suppresses the year/month/day defaults that method would apply.
+ return getDateTimeFormatter(locale, `date-${dateStyle}`, { dateStyle }).format(parsedDate);
} else if (dateStyle === "none" && timeStyle !== "none") {
- // Format only the time
- try {
- return parsedDate.toLocaleTimeString(locale, { timeStyle });
- } catch (e) {
- return parsedDate.toLocaleTimeString(undefined, { timeStyle });
- }
+ // Format only the time; likewise equivalent to parsedDate.toLocaleTimeString(locale, { timeStyle }).
+ return getDateTimeFormatter(locale, `time-${timeStyle}`, { timeStyle }).format(parsedDate);
}
throw new Error("Incorrect state.");
@@ -113,22 +100,55 @@ export function formatDateNumeric(date: string | Date | number | null | undefine
formatOptions.minute = "2-digit";
}
- try {
- return new Intl.DateTimeFormat(locale, formatOptions).format(parsedDate);
- } catch (e) {
- // An unusable locale (e.g. the dev-only "en_rtl", which normalizes to the invalid "en-rtl")
- // makes the constructor throw; fall back to the environment default.
- return new Intl.DateTimeFormat(undefined, formatOptions).format(parsedDate);
+ return getDateTimeFormatter(locale, withTime ? "numeric-with-time" : "numeric", formatOptions).format(parsedDate);
+}
+
+/**
+ * Formatters are memoized because building one costs roughly thirty times what using one does --
+ * `Intl.DateTimeFormat` resolves and parses the locale's CLDR data in its constructor, then formats
+ * in microseconds. A dialog formatting a single date never noticed; a collection view formatting one
+ * per row repeated that construction for every row of every redraw, measured at 158ms per 949-card
+ * board redraw against 4.8ms once cached (see `formatters.bench.ts`).
+ *
+ * `variant` names the option set, and the locale is part of the key, so changing the formatting
+ * locale starts filling fresh entries rather than serving stale ones. That bounds the map at the
+ * selectable locales times the handful of variants the callers above ask for.
+ */
+const dateTimeFormatterCache = new Map<string, Intl.DateTimeFormat>();
+
+/** Memoized per locale: the hour cycle is a property of the locale, never of the date being shown. */
+const twelveHourLocaleCache = new Map<string, boolean>();
+
+function getDateTimeFormatter(locale: string, variant: string, formatOptions: Intl.DateTimeFormatOptions) {
+ const cacheKey = `${locale}|${variant}`;
+
+ let formatter = dateTimeFormatterCache.get(cacheKey);
+ if (!formatter) {
+ try {
+ formatter = new Intl.DateTimeFormat(locale, formatOptions);
+ } catch {
+ // An unusable locale (e.g. the dev-only "en_rtl", which normalizes to the invalid
+ // "en-rtl") makes the constructor throw; fall back to the environment default. Whether
+ // it throws depends only on the locale, so the fallback caches under the same key.
+ formatter = new Intl.DateTimeFormat(undefined, formatOptions);
+ }
+
+ dateTimeFormatterCache.set(cacheKey, formatter);
}
+
+ return formatter;
}
function is12HourLocale(locale: string) {
- try {
- return isTwelveHourCycle(new Intl.DateTimeFormat(locale, { hour: "numeric" }));
- } catch (e) {
- // Same unusable-locale fallback as the caller, so both agree on which cycle is in play.
- return isTwelveHourCycle(new Intl.DateTimeFormat(undefined, { hour: "numeric" }));
+ let is12Hour = twelveHourLocaleCache.get(locale);
+ if (is12Hour === undefined) {
+ // Shares the formatter cache, so the probe costs a construction once per locale rather than
+ // one on every formatDateNumeric() call that asks for a time.
+ is12Hour = isTwelveHourCycle(getDateTimeFormatter(locale, "hour-numeric", { hour: "numeric" }));
+ twelveHourLocaleCache.set(locale, is12Hour);
}
+
+ return is12Hour;
}
function isTwelveHourCycle(formatter: Intl.DateTimeFormat) {