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);
}