A question on performance (article related)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

A question on performance (article related)

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

Yeah, so just as I thought the article overemphasized it for no real reason. Thanks.
Post Reply