Skip to content

Commit

Permalink
Perf: Use computed offset passed in DateTime constructor (#1576)
Browse files Browse the repository at this point in the history
* Add benchmark for DateTime.local with zone

* Use computed offset passed in DateTime constructor

All calls to the datetime constructor that pass an offset (o), have just
computed that offset (quickDT, fromObject) except for clone(). Clone
passes an "old" option to determine whether previous offset can be
reused. If we have config.o, but config.old is not set, then we can use
o without computing it.

This saves an expensive call to zone.offset that duplicates work that
was done immediately prior.
  • Loading branch information
schleyfox authored Mar 9, 2024
1 parent 69032e6 commit 343b061
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
5 changes: 4 additions & 1 deletion benchmarks/datetime.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function runDateTimeSuite() {
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 @@ -20,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 Down
4 changes: 3 additions & 1 deletion src/datetime.js
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,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

0 comments on commit 343b061

Please sign in to comment.