skip to Main Content

I am using Symfony 6 and Doctrine and I want to check if a specific entry in my database exists.

ExampleEntity

  • id
  • field1
  • field2

I want to check if an entity with field2='test' exists in the database.

What will be faster? And why?

$value='test';

## countBy()
$count = $repository->countBy(['field2' => $value]);
if($count > 0) { return true;}

## findBy()
$entity = $repository->findOneBy(['field2' => $value]);
if($entity) { return true;}

2

Answers


  1. In Symfony 6 and Doctrine:

    Use countBy() for a quick check if an entity exists based on specific criteria. It’s efficient as it counts matching records directly without retrieving full entities.

    Choose findOneBy() when you need to work with the entity’s data after confirming its existence. It fetches the entire entity, allowing access to its properties. However, it’s less efficient due to data retrieval.

    For an authentic decision, consider your use case: simple existence check or data interaction. Prioritize performance by benchmarking both methods in your application.

    Login or Signup to reply.
  2. Symfony 6.3 nor Doctrine have a countBy method. However, if instead we used count() — which is what I presume you mean…

    When it comes to performance, there is no clear winner based on your hypothetical example.

    The reason is that fundamentally the two function differently. FindByOne will stop traveling as soon as it finds a match, whereas Count will travel the entire table. Now Count has some internal optimizations within SQL that makes it more performant than even FindByOne when the result (hit) is near the end of the table.

    This carries over to real world tests — when I take a database of 50,000 records, if the "hit" is near the front, then FindByOne finishes nearly 3x faster than Count, however when the "hit" is near the end, then FindByOne finishes 50% slower than Count. And if the "hit" was near the middle, then Count again wins by a margin. But all of this is still measured in the single digit milliseconds (ms)

    Considering that in most cases you probably will not know where the match will be found, using Count will probably be faster more often than not if you’re simply trying to confirm if an entry exists.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search