-4
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');

Can anyone tell me which is faster, recommended and takes less memory in huge operations in php file. I think its DateInterval PID. Any experienced developer?

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39

2 Answers2

2

To benchmark code, you can use microtime()

http://php.net/manual/en/function.microtime.php

<?php

echo 'modify: ';
$time = microtime(1);
for ($x = 0; $x < 10000; $x++) {
    $datetime = new DateTime('2013-01-29');
    $datetime->modify('+1 day');
}
echo $datetime->format('Y-m-d H:i:s'); 
$end = microtime(1);
$time = $end - $time;
echo $time . "\n";

echo 'interval: ';
$time = microtime(1);
for ($x = 0; $x < 10000; $x++) {
    $datetime = new DateTime('2013-01-29');
    $datetime->add(new DateInterval('P1D'));
}
$end = microtime(1);
$time = $end - $time;
echo $time . "\n";

This outputs :

modify: 0.039623975753784 
interval: 0.036103963851929

As you can see, after performing the calculation 10,000 times on each, DateInterval is the faster code. However, this is what I would call a microoptimisation! There isn't much difference!

See it working here https://3v4l.org/pCecn

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
-2
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

This is faster because, in DateInterval, you will need to use interval specification which is hard to read.

Devendra526
  • 7
  • 1
  • 1
  • 3