Skip to content

Commit

Permalink
Perf: Memoize digitsRegex (#1581)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
schleyfox authored Mar 9, 2024
1 parent 41efa73 commit 6b0ec2e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/impl/digits.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@ export function parseDigits(str) {
}
}

// cache of {numberingSystem: {append: regex}}
let digitRegexCache = {};
export function resetDigitRegexCache() {
digitRegexCache = {};
}

export function digitRegex({ numberingSystem }, append = "") {
return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
const ns = numberingSystem || "latn";

if (!digitRegexCache[ns]) {
digitRegexCache[ns] = {};
}
if (!digitRegexCache[ns][append]) {
digitRegexCache[ns][append] = new RegExp(`${numberingSystems[ns]}${append}`);
}

return digitRegexCache[ns][append];
}
2 changes: 2 additions & 0 deletions src/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Locale from "./impl/locale.js";

import { normalizeZone } from "./impl/zoneUtil.js";
import { validateWeekSettings } from "./impl/util.js";
import { resetDigitRegexCache } from "./impl/digits.js";

let now = () => Date.now(),
defaultZone = "system",
Expand Down Expand Up @@ -171,5 +172,6 @@ export default class Settings {
static resetCaches() {
Locale.resetCache();
IANAZone.resetCache();
resetDigitRegexCache();
}
}

0 comments on commit 6b0ec2e

Please sign in to comment.