Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(@formatjs/ecma402-abstract): cache NumberFormat instances for 20x speed-up when formatting dates #2827

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions packages/ecma402-abstract/DateTimeFormat/FormatDateTimePattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,27 @@ export interface FormatDateTimePatternImplDetails {
getDefaultTimeZone(): string
}

const numberFormatsCache = new Map<
string,
[Intl.NumberFormat, Intl.NumberFormat]
>()

function getNumberFormatsForLocale(locale: string) {
const cache = numberFormatsCache.get(locale)
if (cache) return cache

const nfOptions = Object.create(null)
nfOptions.useGrouping = false

const nf = new Intl.NumberFormat(locale, nfOptions)
const nf2Options = Object.create(null)
nf2Options.minimumIntegerDigits = 2
nf2Options.useGrouping = false
const nf2 = new Intl.NumberFormat(locale, nf2Options)
numberFormatsCache.set(locale, [nf, nf2])
return [nf, nf2]
}

/**
* https://tc39.es/ecma402/#sec-partitiondatetimepattern
* @param dtf
Expand All @@ -72,16 +93,7 @@ export function FormatDateTimePattern(
const dataLocale = internalSlots.dataLocale
const dataLocaleData = localeData[dataLocale]
/** IMPL END */

const locale = internalSlots.locale
const nfOptions = Object.create(null)
nfOptions.useGrouping = false

const nf = new Intl.NumberFormat(locale, nfOptions)
const nf2Options = Object.create(null)
nf2Options.minimumIntegerDigits = 2
nf2Options.useGrouping = false
const nf2 = new Intl.NumberFormat(locale, nf2Options)
const [nf, nf2] = getNumberFormatsForLocale(internalSlots.locale)
const tm = ToLocalTime(
x,
// @ts-ignore
Expand Down