Tuesday, 26 April 2011

Efficient Age From Date of Birth Calculation - PHP edition

Well thought I would have a look at the same set of methods in PHP as I did in MS SQL.  The order of efficiency did change somewhat, which was certainly interesting to me.  Below is my simple code.

$timeformatted = date("Y-m-d",strtotime('20th March 1954'));


//Start test 1
$time_start = microtime(true);


$datetime1 = new DateTime($timeformatted);
$datetime2 = new DateTime("now");
$interval = date_diff($datetime1, $datetime2);
echo "Test1".$interval->y;


$time_end = microtime(true);
$time = ($time_end - $time_start)*100;
echo "$time ms";


//start test2
$time_start2 = microtime(true);


$japDate1 = str_replace("-","",$timeformatted);
$japDate2 = date("Ymd",time());


$answer = floor(($japDate2 - $japDate1)/10000);
echo "Test2 $answer";
$time_end2 = microtime(true);
$time2 = ($time_end2 - $time_start2)*100;
echo "$time2 ms";


//start test 3
$time_start3 = microtime(true);


$japDate3 = explode("-",$timeformatted);
$japDate4 = date("Y-m-d",time());
$japDate5 = explode("-",$japDate4);


if($japDate3[1]>$japDate5[1]|| ($japDate3[1]==$japDate5[1] && $japDate3[2]>=$japDate5[2])){
  $answer3 = $japDate5[0] - $japDate3[0] - 1;
} else {
  $answer3 = $japDate5[0] - $japDate3[0];
}


echo "Test3 $answer3";
$time_end3 = microtime(true);
$time3 = ($time_end3 - $time_start3)*100;
echo "$time3 ms";

On my work PC this generated the following timings

Test 1: 0.021505355834961 ms
Test 2: 0.010085105895996 ms
Test 3: 0.010514259338379 ms

Well as you can see for all intents and purposes test 2 and test 3 are equal in performance, and test 1 performs at half the speed.  Although test 1 is definitely the poorest at producing ages, obviously if you were to re-use the data objects later within the same section of code for additional purposes such as a birthday count down, then the expensive data object creation time could end up being as efficient as the other versions.

It is interesting the difference in performance between the two systems, and it suggests that as a generic solution that subtracting the date of birth in Japanese date format is generally the most efficient method across languages and easiest to understand.

No comments: