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: Summary of all perf changes. DO NOT MERGE. #1584

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
15 changes: 14 additions & 1 deletion benchmarks/datetime.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ function runDateTimeSuite() {

const dt = DateTime.now();

const formatParser = DateTime.buildFormatParser("yyyy/MM/dd HH:mm:ss.SSS");

suite
.add("DateTime.local", () => {
.add("DateTime.now", () => {
DateTime.now();
})
.add("DateTime.fromObject with locale", () => {
Expand All @@ -18,6 +20,9 @@ function runDateTimeSuite() {
.add("DateTime.local with numbers", () => {
DateTime.local(2017, 5, 15);
})
.add("DateTime.local with numbers and zone", () => {
DateTime.local(2017, 5, 15, 11, 7, 35, { zone: "America/New_York" });
})
.add("DateTime.fromISO", () => {
DateTime.fromISO("1982-05-25T09:10:11.445Z");
})
Expand All @@ -32,6 +37,14 @@ function runDateTimeSuite() {
zone: "America/Los_Angeles",
});
})
.add("DateTime.fromFormatParser", () => {
DateTime.fromFormatParser("1982/05/25 09:10:11.445", formatParser);
})
.add("DateTime.fromFormatParser with zone", () => {
DateTime.fromFormatParser("1982/05/25 09:10:11.445", formatParser, {
zone: "America/Los_Angeles",
});
})
.add("DateTime#setZone", () => {
dt.setZone("America/Los_Angeles");
})
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
"format-check": "prettier --check 'src/**/*.js' 'test/**/*.js' 'benchmarks/*.js'",
"benchmark": "node benchmarks/index.js",
"codecov": "codecov",
"prepack": "babel-node tasks/buildAll.js",
"prepare": "husky install",
"postinstall": "husky install || exit 0",
"prepare": "babel-node tasks/buildAll.js",
"show-site": "http-server build"
},
"lint-staged": {
Expand Down
132 changes: 126 additions & 6 deletions src/datetime.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
explainFromTokens,
formatOptsToTokens,
expandMacroTokens,
TokenParser,
} from "./impl/tokenParser.js";
import {
gregorianToWeek,
Expand Down Expand Up @@ -369,13 +370,46 @@ function normalizeUnitWithLocalWeeks(unit) {
}
}

// cache offsets for zones based on the current timestamp when this function is
// first called. When we are handling a datetime from components like (year,
// month, day, hour) in a time zone, we need a guess about what the timezone
// offset is so that we can convert into a UTC timestamp. One way is to find the
// offset of now in the zone. The actual date may have a different offset (for
// example, if we handle a date in June while we're in December in a zone that
// observes DST), but we can check and adjust that.
//
// When handling many dates, calculating the offset for now every time is
// expensive. It's just a guess, so we can cache the offset to use even if we
// are right on a time change boundary (we'll just correct in the other
// direction). Using a timestamp from first read is a slight optimization for
// handling dates close to the current date, since those dates will usually be
// in the same offset (we could set the timestamp statically, instead). We use a
// single timestamp for all zones to make things a bit more predictable.
//
// This is safe for quickDT (used by local() and utc()) because we don't fill in
// higher-order units from tsNow (as we do in fromObject, this requires that
// offset is calculated from tsNow).
function guessOffsetForZone(zone) {
if (!DateTime._zoneOffsetGuessCache[zone]) {
if (DateTime._zoneOffsetTs === undefined) {
DateTime._zoneOffsetTs = Settings.now();
}

DateTime._zoneOffsetGuessCache[zone] = zone.offset(DateTime._zoneOffsetTs);
}
return DateTime._zoneOffsetGuessCache[zone];
}

// this is a dumbed down version of fromObject() that runs about 60% faster
// but doesn't do any validation, makes a bunch of assumptions about what units
// are present, and so on.
function quickDT(obj, opts) {
const zone = normalizeZone(opts.zone, Settings.defaultZone),
loc = Locale.fromObject(opts),
tsNow = Settings.now();
const zone = normalizeZone(opts.zone, Settings.defaultZone);
if (!zone.isValid) {
return DateTime.invalid(unsupportedZone(zone));
}

const loc = Locale.fromObject(opts);

let ts, o;

Expand All @@ -392,10 +426,10 @@ function quickDT(obj, opts) {
return DateTime.invalid(invalid);
}

const offsetProvis = zone.offset(tsNow);
const offsetProvis = guessOffsetForZone(zone);
[ts, o] = objToTS(obj, offsetProvis, zone);
} else {
ts = tsNow;
ts = Settings.now();
}

return new DateTime({ ts, zone, loc, o });
Expand Down Expand Up @@ -487,7 +521,9 @@ export default class DateTime {
if (unchanged) {
[c, o] = [config.old.c, config.old.o];
} else {
const ot = zone.offset(this.ts);
// If an offset has been passed and we have not been called from
// clone(), we can trust it and avoid the offset calculation.
const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
c = tsToObj(this.ts, ot);
invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
c = invalid ? null : c;
Expand Down Expand Up @@ -529,6 +565,22 @@ export default class DateTime {
this.isLuxonDateTime = true;
}

/**
* Timestamp to use for cached zone offset guesses (exposed for test)
*
* @access private
*/
static _zoneOffsetTs;
/**
* Cache for zone offset guesses (exposed for test).
*
* This optimizes quickDT via guessOffsetForZone to avoid repeated calls of
* zone.offset().
*
* @access private
*/
static _zoneOffsetGuessCache = {};

// CONSTRUCT

/**
Expand Down Expand Up @@ -2229,6 +2281,74 @@ export default class DateTime {
return DateTime.fromFormatExplain(text, fmt, options);
}

/**
* Build a parser for `fmt` using the given locale. This parser can be passed
* to {@link DateTime.fromFormatParser} to a parse a date in this format. This
* can be used to optimize cases where many dates need to be parsed in a
* specific format.
*
* @param {String} fmt - the format the string is expected to be in (see
* description)
* @param {Object} options - options used to set locale and numberingSystem
* for parser
* @returns {TokenParser} - opaque object to be used
*/
static buildFormatParser(fmt, options = {}) {
const { locale = null, numberingSystem = null } = options,
localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true,
});
return new TokenParser(localeToUse, fmt);
}

/**
* Create a DateTime from an input string and format parser.
*
* The format parser must have been created with the same locale as this call.
*
* @param {String} text - the string to parse
* @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}
* @param {Object} opts - options taken by fromFormat()
* @returns {DateTime}
*/
static fromFormatParser(text, formatParser, opts = {}) {
if (isUndefined(text) || isUndefined(formatParser)) {
throw new InvalidArgumentError(
"fromFormatParser requires an input string and a format parser"
);
}
const { locale = null, numberingSystem = null } = opts,
localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true,
});

if (!localeToUse.equals(formatParser.locale)) {
throw new InvalidArgumentError(
`fromFormatParser called with a locale of ${localeToUse}, ` +
`but the format parser was created for ${formatParser.locale}`
);
}

const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text);

if (invalidReason) {
return DateTime.invalid(invalidReason);
} else {
return parseDataToDateTime(
result,
zone,
opts,
`format ${formatParser.format}`,
text,
specificOffset
);
}
}

// FORMAT PRESETS

/**
Expand Down
14 changes: 13 additions & 1 deletion src/impl/digits.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@ export function parseDigits(str) {
}
}

// cache of {numberingSystem: {append: regex}}
const 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];
}
4 changes: 4 additions & 0 deletions src/impl/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -539,4 +539,8 @@ export default class Locale {
this.outputCalendar === other.outputCalendar
);
}

toString() {
return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`;
}
}
68 changes: 50 additions & 18 deletions src/impl/tokenParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -432,27 +432,59 @@ export function expandMacroTokens(tokens, locale) {
* @private
*/

export function explainFromTokens(locale, input, format) {
const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),
units = tokens.map((t) => unitForToken(t, locale)),
disqualifyingUnit = units.find((t) => t.invalidReason);
export class TokenParser {
constructor(locale, format) {
this.locale = locale;
this.format = format;
this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale);
this.units = this.tokens.map((t) => unitForToken(t, locale));
this.disqualifyingUnit = this.units.find((t) => t.invalidReason);

if (!this.disqualifyingUnit) {
const [regexString, handlers] = buildRegex(this.units);
this.regex = RegExp(regexString, "i");
this.handlers = handlers;
}
}

if (disqualifyingUnit) {
return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };
} else {
const [regexString, handlers] = buildRegex(units),
regex = RegExp(regexString, "i"),
[rawMatches, matches] = match(input, regex, handlers),
[result, zone, specificOffset] = matches
? dateTimeFromMatches(matches)
: [null, null, undefined];
if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
throw new ConflictingSpecificationError(
"Can't include meridiem when specifying 24-hour format"
);
explainFromTokens(input) {
if (!this.isValid) {
return { input, tokens: this.tokens, invalidReason: this.invalidReason };
} else {
const [rawMatches, matches] = match(input, this.regex, this.handlers),
[result, zone, specificOffset] = matches
? dateTimeFromMatches(matches)
: [null, null, undefined];
if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
throw new ConflictingSpecificationError(
"Can't include meridiem when specifying 24-hour format"
);
}
return {
input,
tokens: this.tokens,
regex: this.regex,
rawMatches,
matches,
result,
zone,
specificOffset,
};
}
return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };
}

get isValid() {
return !this.disqualifyingUnit;
}

get invalidReason() {
return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;
}
}

export function explainFromTokens(locale, input, format) {
const parser = new TokenParser(locale, format);
return parser.explainFromTokens(input);
}

export function parseFromTokens(locale, input, format) {
Expand Down
Loading