I'm using Laravel 5.2 for a project I'm working on. Does anyone have any tips regarding how I can leverage Laravel to make this loop run more quickly?
foreach ($purchaseYears as $purchaseYear){
$totalInventory = \App\Inventory::where('purchase_year', $purchaseYear)->count();
if ($purchaseYear < 1960) { $purchaseYear = 'Pre 1960'; }
else if ($purchaseYear >= 1960 && $purchaseYear < 1965) { $purchaseYear = '1960-64'; }
else if ($purchaseYear >= 1965 && $purchaseYear < 1970) { $purchaseYear = '1965-69'; }
else if ($purchaseYear >= 1970 && $purchaseYear < 1975) { $purchaseYear = '1970-74'; }
else if ($purchaseYear >= 1975 && $purchaseYear < 1980) { $purchaseYear = '1975-79'; }
else if ($purchaseYear >= 1980 && $purchaseYear < 1985) { $purchaseYear = '1980-84'; }
else if ($purchaseYear >= 1985 && $purchaseYear < 1990) { $purchaseYear = '1985-89'; }
else if ($purchaseYear >= 1990 && $purchaseYear < 1995) { $purchaseYear = '1990-94'; }
else if ($purchaseYear >= 1995 && $purchaseYear < 2000) { $purchaseYear = '1995-99'; }
else if ($purchaseYear >= 2000 && $purchaseYear < 2005) { $purchaseYear = '2000-04'; }
else if ($purchaseYear >= 2005 && $purchaseYear < 2010) { $purchaseYear = '2005-09'; }
else if ($purchaseYear >= 2010 && $purchaseYear < 2015) { $purchaseYear = '2010-14'; }
else if ($purchaseYear >= 2015 && $purchaseYear < 2019) { $purchaseYear = '2015-19'; }
if (isset($chartData[$purchaseYear])) {
$prev = $chartData[$purchaseYear];
$chartData[$purchaseYear] = $totalInventory + $prev;
$prev = null;
} else {
$chartData[$purchaseYear] = $totalInventory;
}
}
答案 0 :(得分:0)
我认为你可以把日期分成一个模式,而不是仅仅测试每个十年,这样的事情:
if ($purchaseYear < 1960) {
$purchaseYear = 'Pre 1960';
} else {
$prefix = substr($purchaseYear,0,2);
$decade = substr($purchaseYear,1,1);
$suffix = substr($purchaseYear,-1);
$purchYear = $prefix . $decade
if ($suffix<5) {
$purchYear .= '0-' . $decade . '4';
} else {
$purchYear .= '5-' . $decade . '9'
}
Haven没有对此进行测试,但我认为它会做你喜欢的事情。
答案 1 :(得分:0)
我认为最耗时的部分应该是执行查询。如果您使用whereIn
,那么我认为您只能执行一次查询,然后循环结果。我没有测试过,但它应该是这样的:
$purchasesByYear = \App\Inventory::select('purchase_year',
DB::raw('count(*) as purchase_count'))
->whereIn('purchase_year', $purchaseYears)
->groupBy('purchase_year')->get();
我认为减少查询执行次数将是阻止其慢慢运行的主要机会。此外,我认为如果您还没有这样做,那么在purchase_year中添加索引应该会有所帮助。
您可以使用一些数学来代替很多其他条件来处理分组年份。这可能实际上稍微慢一些,但代码重复性稍差,我相信你对这部分所做的任何事情都将是微观优化,而不是你可以对查询部分做什么。我的建议是:
foreach ($purchasesByYear as $purchaseYear) {
$year = $purchaseYear->purchase_year;
if ($year < 1960) {
$yearRange = 'Pre 1960';
} else {
// subtract one until the year is a multiple of five
while ($year % 5) { $year--; }
// then construct the range string using the starting number
$yearRange = $year.'-'.($year+4);
}
if (isset($chartData[$yearRange])) {
$chartData[$yearRange] += $purchaseYear->purchase_count;
} else {
$chartData[$yearRange] = $purchaseYear->purchase_count;
}
}