Magento – Get product FINAL price without loading entire product

attributesmagento-1.9priceproduct-collectionspecial-price

I can get product attributes efficiently without loading the entire product by using:

Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);

However, I can only do this with the price 'attribute, since final_price is technically not an attribute. Since I'm grabbing a few hundred products on one page load, and the only data I need is the product's final price, doing this is very inefficient:

foreach($productIds as $productId) {
    $finalPrice = Mage::getModel('catalog/product')->load($productId)->getFinalPrice();
    ....
}

Since I'm loading the entire product. If anybody can suggest a more efficient way, I would really appreciate it. Cheers!

Best Answer

"a more efficient way" is to use product collcections where final price is already add to. Some numbers here: What is faster - getting raw attribute value or use collection?

Using ->addFinalPrice() will add something like this to collection query ...

, price_index.price, price_index.tax_class_id, price_index.final_price, IF(price_index.tier_price IS NOT NULL, LEAST(price_index.min_price, price_index.tier_price), price_index.min_price) AS minimal_price, price_index.min_price, price_index.max_price, price_index.tier_price

and

INNER JOIN catalog_product_index_price AS price_index ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0

I'd us a colletion like

$collection = Mage::getResourceModel('catalog/product_collection')
    ->addIdFilter($productIds)
    ->addFinalPrice();

foreach ($collection as $product) {
    $finalPrices[] = $product->getFinalPrice();
}
  • Total Incl. Wall Time (microsec): 2,131,092 microsecs
  • Total Incl. CPU (microsecs): 2,109,925 microsecs
  • Total Incl. MemUse (bytes): 4,776,976 bytes
  • Total Incl. PeakMemUse (bytes): 4,829,112 bytes
  • Number of Function Calls: 103,275

compared to

foreach($productIds as $productId) {
    $finalPrices[] = Mage::getModel('catalog/product')->load($productId)->getFinalPrice();
}
  • Total Incl. Wall Time (microsec): 116,555,318 microsecs
  • Total Incl. CPU (microsecs): 114,323,845 microsecs
  • Total Incl. MemUse (bytes): 22,853,768 bytes
  • Total Incl. PeakMemUse (bytes): 23,126,448 bytes
  • Number of Function Calls: 5,465,676