Page 1 of 1

A question on performance (article related)

Posted: Sun Mar 19, 2006 10:21 am
by Ree
I accidentally found this article: http://www.devarticles.com/c/a/PHP/Buil ... ith-PHP/1/

I read it and now I've got a question regarding the inefficiency it describes. Here are the two code snippets. The first is inefficient and slow (according to the article), and the second one is the correct one.

Code: Select all

function getEmployees()
{
  $query = "SELECT id FROM persons WHERE companyid = $this->companyid";
  $stmt = execute_query($query);
  $this->employees = array();
  while ($row = fetch_object($stmt)
  {
    $this->employess[$row->id] = new Person($row->id);
  }
  return $this->employees;
}

$company = new Company("Datagate");
$employees = $company->getEmployees();
foreach ($employees as $id =>$employee)
{
  $employee->addVacationDays(3);
}

Code: Select all

function getEmployees()
{
  $query = "SELECT id FROM persons WHERE companyid = $this->companyid";
  $stmt = execute_query($query);
  $this->employees = array();
  while ($row = fetch_object($stmt)
  {
    $this->employess[$row->id] = $row->id;
  }
  return $this->employees;
}

$company = new Company("Datagate");
$employees = $company->getEmployees();
foreach ($employees as $id)
{
  $employee = new Employee($id);
  $employee->addVacationDays(3);
}
Actually I don't see the horrible inefficiency the article describes. Do you?

Posted: Sun Mar 19, 2006 11:05 am
by feyd
there's no major difference really. The first front-loads the time, while the second back-loads it. But both must do the same work, apparently. Now, in a larger application, it could be more efficient to do the second one, but it the first can be more efficient, depending very heavily on how the code was written.

Posted: Sun Mar 19, 2006 11:29 am
by Ree
Yeah, so just as I thought the article overemphasized it for no real reason. Thanks.