I have a helper method in Magento which requires me to get the count of several unrelated collections. Further to this, i need this information for each product in a category i.e. for each product in the product list view. So i will potentially be creating lots of collections repeatedly during the product list rendering.
What is the most efficient method of getting the count of a collection, that is, i do not need any data from the models, simply how many models there are.
Is it simply:
Mage::getResourceModel('mymodule/mymodel_collection')->addFilter('myattribute', $value)->count()
Or is there a more efficient way to do this?
Very good question. From what I found in the source code, this is the fastest option, even though it does the following in Varien_Data_Collection:
So it does its usual thing and goes ahead and loads whatever you specified, just like it would do if you iterated over the individual items. No magic SQL
COUNT()here. The only other methods I’ve found that have something to do with counting products aregetSelectCountSql()andgetProductCountSelect(), but they just return SQL code.But: the whole EAV thing and Magento’s query builder are very smart, so that shouldn’t be that big of a deal. Also, I would bet that Magento has all kinds of caching going on.
So in short: yes, it is the fastest option to count the number of products in a product collection.