Question

Which of these methods is "easier" on the Magento platform, specifically the database? Method 1 uses a single call to the database to retrieve the collection, and then iterates over the result. Method 2 retrieves the product inside the loop on each run.

Method 1

$products = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*') // <- obv a bad idea
    ->addAttributeToFilter(
        'sku', array('in' => $productSkus)
    )
    ->load();

foreach ($products as $product) {
    echo $product->getName();
}

Versus getting the product object inside the loop:

Method 2

$products = Mage::getModel('catalog/product');

foreach ($array as $key => value) {
    $product = $products->load('PROD001', 'sku');
}

Obviously this code is only a sample. Considering the dataset could contain many hundreds or thousands of products, which method is the "right" way, or is there another I'm missing?

Was it helpful?

Solution

Method 1 is going to take a lot less time to loop through, but will consume a lot of memory.

Another option which is probably the one you are looking for is using the:

Mage::getSingleton('core/resource_iterator')

This describes it sort of: Is it possible to iterate over Magento collections with pagination natively?

Make sure to pay attention to Batched Iterator by Kalen Jordan https://gist.github.com/kalenjordan/5483065

This can be used to accomplish very large datasets elegantly.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top