【发布时间】:2020-02-26 13:43:23
【问题描述】:
我在比较多个数组时遇到了性能缓慢的问题。
我做的算法是:
我将首先通过 foreach 循环数组
foreach($branches as $index => $branch) {
if (!$identical) {
continue;
}
// Basically this $permissions will be fetching data from the database.
$permissions = $this->get()
->where('user_id', $userId)
->where('branch_id', $userBranchId)
->sortBy('permission_id')
->pluck(['permission_id']);
// if index = 0 then I'll initialize the temporary variable (ARRAY) $initial otherwise I'll compare two variable (ARRAY)
if ($index === 0) {
$initial = $permissions;
} else {
if ($initial != $permissions) {
$identical = false;
}
}
}
所以要比较多个数组,我只使用这个 if 条件和比较符号 (==)。但我在想如果
【问题讨论】:
-
这取决于原始数组的来源。此时可以进行此处理,而不必遍历数组并在那里检查详细信息。为了提高性能,尽可能减少数据库调用的次数通常会更快。
-
这段代码的最佳解决方案是删除它,因为它什么都不做。
标签: php laravel optimization