From 77bf4636344a2d79d970f68893a17e5d0bf63c11 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Sep 2026 09:02:02 +0000 Subject: [PATCH] fixTimezoneShift: cache the Intl.DateTimeFormat instance Addresses a Copilot review finding on buzz-code/react-admin-nestjs#167: getTimeZoneOffsetMinutes constructed a fresh Intl.DateTimeFormat on every call (up to 3x per date column per row), which is comparatively expensive and unnecessary since the formatter is stateless across the dates it formats. Cache one instance per timezone instead. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01KeX6BFe7P4pHLPm3VwFjPn --- utils/entity/fixTimezoneShift.util.ts | 35 ++++++++++++++++++--------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/utils/entity/fixTimezoneShift.util.ts b/utils/entity/fixTimezoneShift.util.ts index a20306c..5af56e1 100644 --- a/utils/entity/fixTimezoneShift.util.ts +++ b/utils/entity/fixTimezoneShift.util.ts @@ -38,18 +38,31 @@ export function reinterpretUtcDigitsAsIsraelLocal(wrongDate: Date): Date { return new Date(guess); } +// Intl.DateTimeFormat construction is comparatively expensive and stateless across +// the dates it formats, so it's built once per timezone and reused - fixTimezoneShift +// calls this up to 3 times per date column, per row. +const timeZoneFormatters = new Map(); + +function getTimeZoneFormatter(timeZone: string): Intl.DateTimeFormat { + let formatter = timeZoneFormatters.get(timeZone); + if (!formatter) { + formatter = new Intl.DateTimeFormat('en-US', { + timeZone, + hourCycle: 'h23', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }); + timeZoneFormatters.set(timeZone, formatter); + } + return formatter; +} + function getTimeZoneOffsetMinutes(timeZone: string, at: Date): number { - const formatter = new Intl.DateTimeFormat('en-US', { - timeZone, - hourCycle: 'h23', - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - }); - const parts = Object.fromEntries(formatter.formatToParts(at).map((p) => [p.type, p.value])); + const parts = Object.fromEntries(getTimeZoneFormatter(timeZone).formatToParts(at).map((p) => [p.type, p.value])); const localDigitsAsUtcMillis = Date.UTC( Number(parts.year), Number(parts.month) - 1,