在我的web应用程序中,我有一个函数立即被执行了100多次,我正在努力寻找一种性能更好的方法。
public static function removeDuplicateFeeds($id, $feeds, $todo)
{
$actionsHistory = ActionsHistory::whereAccountId($id)->whereActionName($todo)->get();
if (!empty($actionsHistory)) {
foreach ($actionsHistory as $history) {
foreach ($feeds as $key => $feed) {
if ($history->action_name == $feed['pk']) {
unset($feeds[$key]);
}
}
}
}
}
我还想从$feeds
中删除$actionsHistory
中的所有元素。
更新:
在此测试代码中,首先将$feeds
数组的索引作为"pk":"7853740779"
存储在我的数据库中,删除重复项后,此项应被删除,但我也将所有$feeds
项都存储到$filteredFeeds
中
$userAccountSource = InstagramAccount::with('user', 'schedule')->get();
$feeds = [
json_decode('{"pk":"7853740779","username":"teachkidss","full_name":"..."}'),
json_decode('{"pk":"7853740709","username":"teachkidss","full_name":"..."}'),
json_decode('{"pk":"7853740009","username":"teachkidss","full_name":"..."}')
];
$filteredFeeds = AnalyzeInstagramPageController::removeDuplicateFeeds($userAccountSource[0]->id, $feeds, 'like');
public function removeDuplicateFeeds($id, $feeds, $todo)
{
$feeds = collect($feeds); // If $feeds is not already a collection
$actionsHistory = ActionsHistory::whereAccountId($id)
->whereActionName($todo)
->whereIn('action_name', $feeds->pluck('pk')) // retrieves only duplicate records
->select('action_name') // reducing the select improves performance
->get(); // Should return a eloquent collection instance
if (!empty($actionsHistory)) {
return $feeds->whereNotIn('pk', $actionsHistory->pluck('action_name'));
}
return $feeds;
}
发布于 2018-07-21 22:06:56
在不知道提要或数据库记录数量的情况下,您必须根据数据集测试这些记录的性能,并查看它们是否具有更高的性能。
public static function removeDuplicateFeeds($id, $feeds, $todo)
{
$feeds = collect($feeds); // If $feeds is not already a collection
$actionsHistory = ActionsHistory::whereAccountId($id)
->whereActionName($todo)
->select('action_name') // reducing the select improves performance
->get(); // Should return an eloquent collection instance
if (!empty($actionsHistory)) {
return $feeds->whereNotIn('pk', $actionsHistory->pluck('action_name'));
}
return $feeds;
}
或者,如果您的数据库查询返回的记录明显多于您拥有的提要,您可以尝试利用mysql更快的查询速度,而不是使用php较慢的array_filter/foreach速度。
public static function removeDuplicateFeeds($id, $feeds, $todo)
{
$feeds = collect($feeds); // If $feeds is not already a collection
$actionsHistory = ActionsHistory::whereAccountId($id)
->whereActionName($todo)
->whereIn('action_name', $feeds->pluck('pk')) // retrieves only duplicate records
->select('action_name') // reducing the select improves performance
->get(); // Should return a eloquent collection instance
if (!empty($actionsHistory)) {
return $feeds->whereNotIn('pk', $actionsHistory->pluck('action_name'));
}
return $feeds;
}
如果这两种方法中的任何一种都有效,那么知道这对你来说有多快将是件好事。让我们知道。祝好运。
发布于 2018-07-22 01:01:07
您可以尝试使用PHP中的array_unique
函数。Source.
发布于 2018-07-22 16:16:14
您可以使用集合中的内置唯一()函数,请在此处查看更多信息:https://laravel.com/docs/5.6/collections#method-unique
这样你就能保持整洁和优雅。
https://stackoverflow.com/questions/51456052
复制相似问题