I have some performance issues in a chartcontroller. I have two arrays: one array with dates and one array with entities which contain also a date. I want to cumulative count the date values of the entities.
I do have a bit of code but it's slow (I have to wait 3 - 4 seconds for 68k rows in the data array).
My code:
// Loop through the SQL results and count on date
foreach ($result as $row) {
foreach ($dates as $date => $value) {
// $row['appointmentDate'] is a DateTime object
if ($date >= $row['appointmentDate']->format('Ymd')) {
$dates[$date]++;
}
}
}
Is there a smarter / better / faster way to achieve this?
// Edit
Jack gived me the push I needed and I solved my performance issue.
The code above took 38000 ms to complete, the code beneath 5700ms.
usort($result, function($a, $b) {
return $a['appointmentDate'] > $b['appointmentDate'];
});
// Loop through the SQL results and count on date
for ($i = 0; $i++; $i <= count($result)) {
$i++;
$dates[$result[$i]['appointmentDate']->format('Ymd')] = $i;
}
Thanks for your help Jack!
Yes. You can achieve a better performance by sorting the two arrays before doing the comparison. With two arrays ordered you can avoid doing a n*m loop, and stay on n+m complexity (plus n*log n and m*log m for sorting, which anyway is less than n*m)