For example I need to get review count, one way of doing it is like this:
public function getActiveReviews() { return $this->getReviews()->filter(function(Review $review) { return $review->isActive() && !$review->isDeleted(); })->count(); }
Another way is to use Query Builder like this:
$qb = $this->createQueryBuilder('r') ->where('r.active = true') ->andWhere('r.deleted = false') ->select('count(r)')
Which way will give me better performance and why?
Advertisement
Answer
Of course count query will be faster because it will result into single SQL query that will return single value.
Iteration over entities will require:
- Run of SQL query for fetching data rows
- Actual fetching of data
- Entity objects instantiation and persisting fetched data into them
Depending on amount of affected data difference may be very big.
The only case when running count over entities may be fast enough is a case when you already have all entities fetched and just need to count them.