Doctrine ORM 2.14: Clearing the identity map to mitigate memory growth
0 reputation · 13 May 2025, 09:23 UTC
Goal
In a long‑running PHP script that loads thousands of entities, memory usage climbs linearly due to the Unit of Work’s identity map. The goal is to keep memory usage stable while still being able to reuse some entity instances.
Constraints
Calling EntityManager::clear() removes all managed entities, which can break subsequent code that expects those objects to remain attached. Detaching individual entities with detach() is an alternative but its effect on overall memory consumption is unclear in a large batch context.
Unresolved Questions
- When processing 10,000+ entities, does repeatedly calling
EntityManager::clear()after each batch of 1,000 provide a measurable memory benefit compared to detaching only the processed entities? - What is the impact on entity lifecycle callbacks (e.g.,
postPersist,preUpdate) whenclear()is used mid‑transaction? - Can we configure Doctrine to automatically purge the identity map after a configurable number of persisted entities without manual intervention?