1

Which is the most efficient method for gathering related data?

Lets say we have multiple projects that are associated to one category 1:M.

Each project holds the ID value of the Category it is a part of. 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.

So for example instead of:

project_id: 1 project_title: first project 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

I'm not having trouble achieving this, I'm curious what the most efficient way to achieve it is.

Option 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

$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.

2
  • why not use SQL for this? i am assuming you have some sort of database so all you need is "select * from projects where category_id = '$category' Commented Nov 18, 2012 at 20:42
  • Sorry, shouldn't have used my prebuilt db helper method in my examples. Those find_all methods essentially do 'select * from projects' Commented Nov 18, 2012 at 20:44

2 Answers 2

1
  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.

Sign up to request clarification or add additional context in comments.

Comments

0

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. Sequential (i.e. read-then-read-the-next-row) read operations on SQL are much quicker than targetted read operations.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.