0

I need to format several thousand Y-m-d H:i:s dates from an API response (sample). I used Xdebug to profile these two approaches.

What I have

foreach ($dates as $date) {
    $dt = new \DateTimeImmutable($date);
    $value = $dt->format('r');
}
Calls                               Count   Total Call Cost
php::DateTimeImmutable->__construct 55800   183 ms  1,79%
php::DateTimeImmutable->format      55800   14 ms   0,14%

What I tried

$dt = new \DateTime;
foreach ($dates as $date) {
    $dt->modify($date);
    $value = $dt->format('r');
}
Calls                       Count   Total Call Cost
php::DateTime->modify       55800   130 ms  1,10%
php::DateTime->format       55800   17 ms   0,14%
php::DateTime->__construct  1       0 ms    0,00%

The latter approach looks slightly more efficient. Is it safe to rely on just modifying the datetime instead of completely redeclaring it?

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
  • 1
    Does a difference of 53ms over 55800 items really warrant this…? – deceze Oct 06 '20 at 07:46
  • IMHO, unless you have a strong reason to squeeze milliseconds you should stick to the code that's easier to understand. Your algorithm is not about altering a given date with an array of dates, yet that's what the `->modify()` version suggest at first sight. – Álvaro González Oct 07 '20 at 15:20

1 Answers1

0

We're talking micro-optimizations, your example with DateTimeImmutable inside the loop is slower because you create a new DateTimeImmutable object each time. It's faster when you create the object outside of the loop obviously. and yes modifying it on each time is safe!

Khaled Alam
  • 885
  • 7
  • 12