Don't Do This At Home #2: Count After Hydration
Can you spot the problem in the following snippet?
The problem is that, if all you need is the number of books, you just wasted a lot of memory. find() issues a SQL SELECT query, iterates over the resultset, and populates ("hydrates") a new book object for each row. If there are 10,000 results to the query, Propel hydrates 10,000 Model objects... for nothing, since all you need is the number of results.
The good way to count the number of results of a query is to use the ModelCriteria::count() method:
Propel also uses count() internally when you call paginate(), so that only the results in the current page get hydrated.
3 comments
Feb 16, 2012
ral said...
I love that Don't Do This At Home series! Working a lot with Propel I think this is very useful, please keep it on!many thanks,
ral