Flush entity manager on object when many objects are in use

Flush entity manager on object when many objects are in use

Update:

The the meantime using an object as parameter for the flus method was deprecated. Turns out, it's also not a good idea to manage this on your own.

What we do now for message queues is to manually clear the entity manager with $entityManager->clear() after running an encapsulated process. This results in the same performance benefits without managing the update process on your own.


When flushing an entity manager in Doctrine, there are two ways to do it. Just flush one element or all objects that entity manager manages.

Usually there is not really a difference in performance. But I now stumbled into a situation where I build a worker which persists new data through an API. To do so I have to query a database and check thousands of objects. I started with using the simple flush() call. As the database grew the process got slower and slower and I wondered why the API was taking so long for one round trip. While debugging I realized that the API roundtrip was still only taking a few milliseconds but it took over 2 seconds every time I updated the new object to the database, because the entity manager had to check all thousands of elements it manages for changes.
So I switched from a simple flush() to flush($status), meaning just the relevant object in question and the storing process only took a few milliseconds.

/**
 * Store status.
 *
 * @param Status $status
 *
 * @throws ORMException
 */
public function store(Status $status): void
{
    $this->getEntityManager()->persist($status);
    $this->getEntityManager()->flush($status);
}