SQL queries inside a loop
Very common bad practice is to load Magento models and process it inside a loop. Running SQL query is very expensive operation, and doing it in a loop tends to make it even worse. Instead of doing that we could use data collections to load models and then process it. We also need to be careful when working with collection to do not exceed memory.
Wrong:
foreach ($this->getProductIds() as $productId){
$product = Mage::getModel('catalog/product')->load($productId);
$this->processProduct($product);
}
Good:
$collection = Mage:getResourceModel('catalog/product_collection')
->addFieldsToFilter('entity_id', array($this->getProductIds()))
->addAttributeToSelect(array('name'));
foreach ($collection as $product){
$this->processProduct($product);
}
Comments
Post a Comment