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?

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.

  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.