Memory errors and slow loading pages

In an other post I talked about a problem I encountered with the way Magento loads addresses before editing. But the problem was bigger than that one page. The problem origins from a deeper problem within Magento. It's the way the getItemById method works.

In the file lib/Varien/Data/Collection.php around line 709 we see the following code:

  1. /**
  2.  * Retrieve item by id
  3.  *
  4.  * @param mixed $idValue
  5.  * @return Varien_Object
  6.  */
  7. public function getItemById($idValue)
  8. {
  9.     $this->load();
  10.     if (isset($this->_items[$idValue])) {
  11.         return $this->_items[$idValue];
  12.     }
  13.     return null;
  14. }

What we see here is that all the items of the collection are loaded and then only one item will get returned. This is not a big problem for small collections, but for large collections like the order addresses this slows your site down or even breaks your site because of memory problems. One option to avoid this is to filter your collection first, but even then there probably will be items loaded from the database that aren't used.

If you only want one item, you can better use the load method instead:

  1. $collection->load($id);

When you do this there will only be one item loaded from the database. This saves memory space and keeps your Magento shop fast.