Skip to content
Advertisement

Will I get better performance if I use COUNT query instead of looping through entities in Symfony 4?

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:

  1. Run of SQL query for fetching data rows
  2. Actual fetching of data
  3. 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement