Collection and select

Sometimes you need to get a lot of information from the database and you need it fast. The way to get this information normally would be to use the Magento collection for the model. It would look like this:

$collection = Mage::getModel('customer/customer')->getCollection()
    ->joinAttribute('billing_city', 'customer/city', 'default_billing', null, 'left');

foreach ($collection as $customer) {
    // Use $customer

The problem with this way of getting the information is that it loads all customer information into memory, which can take a long time when you have many customers.

The solution to this performance problem is that you read the customers one at a time by using the select that was created.

$select = $collection->getSelect();
$stmt = $select->query();

while ($row = $stmt->fetch()) {
    // Use $row

This is often many times faster and won't fill your memory.



My name is Peter Stuifzand. You're reading my personal website.


Peter Stuifzand
Zwolle, The Netherlands