在PHP累计计数性能下降 [英] Slow performance with cumulative count in PHP
问题描述
我有一个chartcontroller一些性能问题。我有两个数组:一个阵列使用日期和一个阵列与其中也包含一个日期的实体。我想累积计数的实体的日期值。
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.
我确实有一点code,但它的速度慢(我必须等待3 - 第4秒钟的数据阵列中的68K行)。
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).
我的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?
//修改
杰克红粉我,我需要推,我解决我的性能问题。
Jack gived me the push I needed and I solved my performance issue.
上面的code 38000了毫秒来完成,code 5700ms之下。
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!
推荐答案
是的。您可以通过做比较之前的两个数组排序实现了更好的性能。
随着两个数组排序就可以避免做的 N * M 循环,并保持在 N + M 的复杂性(加 N *日志N 和< STRONG> M * log M的<进行排序,这无论如何是小于N * M)/ STRONG>
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)
这篇关于在PHP累计计数性能下降的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!