Mini Tutorial:
How to get product’s attribute with getAttributeRawValue() in Magento

I recently discovered a pretty nice function to retrieve the value of a product’s attribute. Welcome Mage::getResourceModel(‘catalog/product’)->getAttributeRawValue($product_id, $attribute_code, $store_id)

$color = Mage::getResourceModel('catalog/product')
->getAttributeRawValue(32, 'color', $current_store_id);

I used to either load the model or use collection to get the wanted attribute if the model doesn’t have it.

$model = Mage::getModel('catalog/product')->load(32);
$color = $model->getColor();

OR

$model = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('color')
->addAttributeToFilter('entity_id',32)
->getFirstItem();

$color = $model->getColor();

Out of curiosity, I did couple simple speed tests on these calls.

---- Sandbox Started ----
Store ID: 1
--- By getAttributeRawValue --
Time: 0.044373
Color: 26
--- By Model --
Time: 0.142007
Color: 26
--- By Collection --
Time: 0.032652
Color: 26
---- Sandbox Ended ----

Surprisingly, collection is faster. What if I have to call those functions 10 times? I imagine some of you would say “Dude! Use collection! You can get them all with single call.” Sometime you are limited by certain conditions. For example, you need some attributes in a override function that only accepts a product_id as parameter. This function runs multiple times through out a page request. This test is handy for such scenario. The result is:

---- Sandbox Started ----
Store ID: 1
--- By getAttributeRawValue --
Time: 0.069474
--- By Collection --
Time: 0.110836
---- Sandbox Ended ----

getAttributeRawValue() is the winner!

What if I want multiple attributes?

$rc = Mage::getResourceModel('catalog/product');
$color = $rc->getAttributeRawValue(32, 'color', $store_id);
$price = $rc->getAttributeRawValue(32, 'price', $store_id);
$name = $rc->getAttributeRawValue(32, 'name', $store_id);
$description = $rc->getAttributeRawValue(32, 'description', $store_id);
$model = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect(array('price','color','name','description'))
->addAttributeToFilter('entity_id',32)
->getFirstItem();
$color = $model->getColor();
$price = $model->getPrice();
$name = $model->getName();
$description = $model->getDescription();

The results are similar to single attribute retrieval. Collection is faster on run once test, and getAttributeRawValue() is faster on run 10 times test. In conclusion, both methods have its pros and cons. I use them depending on any condition and restriction. Please leave comment if you have a better method or a question to share!