简体   繁体   English

我应该多次访问数据库还是遍历数组?

[英]Should I access the database multiple times or loop through an array?

Which is the most efficient method for gathering related data? 哪个是收集相关数据的最有效方法?

Lets say we have multiple projects that are associated to one category 1:M. 可以说我们有多个与一个类别1:M相关的项目。

Each project holds the ID value of the Category it is a part of. 每个项目都拥有其所属类别的ID值。 I have an array object of all my projects, I now want to add to that array object its category name rather than its ID. 我的所有项目都有一个数组对象,现在我要在该数组对象中添加其类别名称而不是其ID。

So for example instead of: 因此,例如,代替:

project_id: 1 project_title: first project project_desc: bla bla project_category_id: 1 project_id:1 project_title:第一个项目project_desc:bla bla project_category_id:1

I want it to be: 我希望它是:

project_id: 1 project_title: first project project_desc: bla bla project_category: first category project_id:1 project_title:第一个项目project_desc:bla bla project_category:第一个类别

I'm not having trouble achieving this, I'm curious what the most efficient way to achieve it is. 我没有遇到困难,我很好奇实现这一目标的最有效方法。

Option 1 选项1

$projects = $this->projects_model->find_all();
$categories = $this->category_model->find_all();

foreach($projects as $project){
   foreach($categories as $category){
      if($project->category_id == $category->id){
         $project->category = $category;
      }
   }
}

Option 2 选项2

$projects = $this->projects_model->find_all();

 foreach($projects as $project){
   $project->category = $this->category_model->find_by('id', $project->category_id);
 }

It's likely there are many other methods for achieving my desired result and potentially in a more efficient manor, if that's the case I'd love to learn. 如果我想学习的话,可能还有很多其他方法可以达到我想要的结果,并且可能以更高效的庄园来实现。

  1. You should profile this yourself and you'll have your answer 您应该自己对此进行配置,然后得到答案

  2. Hitting the database is expensive. 打数据库很昂贵。 Accessing arrays data is not. 不能访问数组数据。 This means you'll want to hit the database as few times as possible. 这意味着您将需要尽可能少地访问数据库。

Assuming your find_all and find_by functions request data from a database, option 1 will be preferable until the ratio between categories sought and categories used becomes low. 假设您的find_all和find_by函数从数据库请求数据,则选项1将是可取的,直到找到的类别和使用的类别之间的比率变低为止。 Sequential (ie read-then-read-the-next-row) read operations on SQL are much quicker than targetted read operations. SQL上的顺序(即先读取然后再读取下一行)读取操作比目标读取操作快得多。

Ultimately, though, if I were you, I would worry less over the actual array looping and more about how you acquire your data, as this is where the performance drain will be. 最终,尽管如此,如果我是您,我将不必担心实际的数组循环,而更多地担心您如何获取数据,因为将导致性能下降。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM