Skip to content

Commit 6b0ec2e

Browse files
authoredMar 9, 2024··
Perf: Memoize digitsRegex (#1581)
* Memoize digitsRegex Profiles reveal that a substantial portion of fromFormat time is spent in digitsRegex. It is only called from unitsForToken and it is always called with 11 suffixes to match different numbers of digits. There are 21 numbering systems, so a fully expanded cache would hold 11*21 = 231 regexes. Benchmarks show about a 1.5x improvement on DateTime.fromFormat * Allow digitRegex cache to be reset
1 parent 41efa73 commit 6b0ec2e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed
 

‎src/impl/digits.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ export function parseDigits(str) {
7070
}
7171
}
7272

73+
// cache of {numberingSystem: {append: regex}}
74+
let digitRegexCache = {};
75+
export function resetDigitRegexCache() {
76+
digitRegexCache = {};
77+
}
78+
7379
export function digitRegex({ numberingSystem }, append = "") {
74-
return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
80+
const ns = numberingSystem || "latn";
81+
82+
if (!digitRegexCache[ns]) {
83+
digitRegexCache[ns] = {};
84+
}
85+
if (!digitRegexCache[ns][append]) {
86+
digitRegexCache[ns][append] = new RegExp(`${numberingSystems[ns]}${append}`);
87+
}
88+
89+
return digitRegexCache[ns][append];
7590
}

‎src/settings.js

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import Locale from "./impl/locale.js";
44

55
import { normalizeZone } from "./impl/zoneUtil.js";
66
import { validateWeekSettings } from "./impl/util.js";
7+
import { resetDigitRegexCache } from "./impl/digits.js";
78

89
let now = () => Date.now(),
910
defaultZone = "system",
@@ -171,5 +172,6 @@ export default class Settings {
171172
static resetCaches() {
172173
Locale.resetCache();
173174
IANAZone.resetCache();
175+
resetDigitRegexCache();
174176
}
175177
}

0 commit comments

Comments
 (0)
Please sign in to comment.