Skip to content

Commit

Permalink
Optimize performance of LocalDate::plusDays(1) calls. (#79)
Browse files Browse the repository at this point in the history
* Optimize performance of LocalDate::plusDays(1) calls.

* Add a comment explaining why there's extra code in LocalDate::plusDays()
  • Loading branch information
gnutix authored Sep 16, 2023
1 parent 8dd2b2c commit f1f432c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/LocalDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,13 @@ public function plusDays(int $days): LocalDate
return $this;
}

// Performance optimization for a common use case.
if ($days === 1) {
return $this->day >= 28 && $this->day === $this->getLengthOfMonth()
? new self($this->year + intdiv($this->month, 12), ($this->month % 12) + 1, 1)
: new self($this->year, $this->month, $this->day + 1);
}

return LocalDate::ofEpochDay($this->toEpochDay() + $days);
}

Expand Down
6 changes: 6 additions & 0 deletions tests/LocalDateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,12 @@ public function providerPlusDays(): array
[2012, 1, 1, 366, 2013, 1, 1],
[2012, 1, 2, -1, 2012, 1, 1],
[2012, 1, 1, -1, 2011, 12, 31],
[2014, 2, 1, 1, 2014, 2, 2],
[2014, 2, 15, 1, 2014, 2, 16],
[2014, 2, 28, 1, 2014, 3, 1],
[2012, 2, 28, 1, 2012, 2, 29],
[2012, 2, 29, 1, 2012, 3, 1],
[2014, 12, 31, 1, 2015, 1, 1],
];
}

Expand Down

0 comments on commit f1f432c

Please sign in to comment.