3

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?

Jongosi
  • 1,511
  • 6
  • 24
  • 41
  • This may be helpful: http://magento.stackexchange.com/questions/3688/gang-of-four-design-patterns-in-magento-core also check out: http://www.coolryan.com/magento/2014/02/20/magento-design-patterns-part-8-iterator/ – Reid Blomquist Mar 11 '14 at 01:15

1 Answers1

9

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.

Aepod
  • 711
  • 3
  • 15
  • Thanks Aepod, using Method 1, with getResourceSingleton() instead of getResourceModel() seems to offer the best of both worlds. – Jongosi Mar 11 '14 at 14:19
  • @Jongosi No that brings nothing good from method 2 and only adds problems instead. The collection resource model has lots of state, you don't want to instantiate it as singleton. – Fabian Schmengler Jun 30 '15 at 15:01