title: Performance penalty php class
body: <p>I am developing a web application for my company. The application is used to keep track of the tools we buy (and use).</p>
  
  <p>Each time a worker in the company is using a tool it is registered in the application (mysql db).
  Until now I have written the code in procedural style. Still a novice in OOP and my procedural code works fine and are relative fast.</p>
  
  <p>Now the application is getting larger and I’m really having issues maintaining my old coding pattern, so I figured it was about time to move on and try implementing OOP. The problem I’m facing now is that I somehow made my classes in a way so the application is up to 10 times slower that before. One of my pages takes 1 sec to load - without the classes it takes 0.1 sec.
  I use php microtime to measure this.</p>
  
  <p>I’ve created a Company class which holds the properties for each company.
  Snippet of the class:</p>
  
  <pre><code>class Company {
  
      private $companyId;
      private $name;
      private $cvr;
      etc…..
  
      private $tools = array();
  
  }
  </code></pre>
  
  <p>So far it’s working as expected. Now I wanted to create a method to get all the companytools and attach it to the $tools array.</p>
  
  <pre><code>public function tools() {
  
      $purchases = $db
      -&gt;table('CompanyTools')
      -&gt;select(
          'id'
      )
      -&gt;where('CompanyTools.companyId', '=', $this-&gt;companyId)
      -&gt;get();
  
      $objects = array();
  
      foreach ($purchases as $purchase) {
  
          $objects[] = new CompanyTool($purchase['id']);
  
      }
  
      $this-&gt;tools = $objects;
  
      return $this-&gt;tools;
  
  }
  </code></pre>
  
  <p>Now when I use it like this I get the performance issues mentioned ealier</p>
  
  <pre><code>foreach ($company-&gt;tools() as $purchase) {
  
      echo $purchase-&gt;id;
  
  }
  </code></pre>
  
  <p>I suspect it has something to do with the loop creating a new instance of the CompanyTool class. The CompanyTool class looks something like this</p>
  
  <pre><code>class CompanyTool {
  
      function __construct($id = null) {
  
      if(!$id) die("We need the id");
  
      $this-&gt;id = $id;
  
      $attributes = $db
          -&gt;table('CompanyTools as ct')
          -&gt;select(
              'ct.*'
          )
          -&gt;where('ct.id', '=', $this-&gt;id)
          -&gt;take(1)
          -&gt;get();
  
      foreach($attributes as $attribute)
          foreach ($attribute as $key =&gt; $value) {
              if(property_exists($this, $key))  $this-&gt;{$key} = $value;
          }
      return $this;       
  
  
  }
  </code></pre>
  
  <p>I hope it's obvious what I'm trying to achieve and my lack of OOP knowledge :)</p>
  
  <p>Thanks for your input</p>
  
  <p>/ j</p>