Doctrine and Memory Consumption: How UnitOfWork and Hydration Can Ruin Your Performance (and How to Avoid It)

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

In the previous article, we looked at how to survive when processing millions of records with Doctrine: using batched flush(), clear(), and toIterable().

But why do those techniques actually work? The answer lies within two internal components of Doctrine that most developers underestimate or simply ignore: the UnitOfWork and the hydration process.

Understanding how these components operate will not only help you optimize batch processes, workers, or exports. It will fundamentally change how you design your code when dealing with large volumes of data.

The Myth: «Doctrine Just Executes SQL and Returns Objects»

Many developers think that this:

$user = $repository->find($id);

basically does three things:

  1. Executes a SELECT * FROM users WHERE id = ?.
  2. Instantiates a User object.
  3. Returns it to you.

The reality is far heavier.

When Doctrine returns an entity, it does not just build a plain object. It constructs and keeps alive an entire ecosystem in memory around it: metadata, snapshots, proxies, the Identity Map, collection references… All of that stays in memory until the EntityManager is destroyed or you call clear().

Identity Map: Doctrine’s Hidden (and Expensive) Cache

Doctrine provides a very useful guarantee: within the same EntityManager, the same database row will always be the exact same PHP instance.

$user1 = $repository->find(10);
$user2 = $repository->find(10);
var_dump($user1 === $user2); // true

It achieves this by maintaining an internal Identity Map: a map containing all loaded entities, indexed by their identifier.

Advantages: prevents duplicates and automatically maintains consistency.

Disadvantage: every entity you load takes up memory. If you run findAll() on 10,000 users, you will hold 10,000 references in that map, even if you only end up using one.

UnitOfWork: The Brain (and Biggest Memory Consumer) of Doctrine

The UnitOfWork (UoW) is Doctrine’s real conductor. It is responsible for:

  • Tracking all entities in the MANAGED state
  • Detecting changes (by comparing them against snapshots)
  • Scheduling database operations
  • Handling cascades and relationships

You can visualize it like this:

$uow = $entityManager->getUnitOfWork();
$managedEntities = $uow->getManagedEntities(); // Cuidado, esto puede ser enorme

The problem is that the more entities you have in the MANAGED state, the more memory the UnitOfWork consumes, and the slower every flush() becomes (because it has to inspect everything).

The Four Entity States (and Their Real Impact on Memory)

Only MANAGED entities add weight to the UnitOfWork. Understanding this is key.

NEW

A freshly instantiated entity. Doctrine is not managing it yet:

$user = new User(); // Sin costo en el UoW

MANAGED

This is where the actual cost starts (whether via persist() or when loaded from the database). Doctrine creates a snapshot, registers it in the Identity Map, and begins tracking changes.

REMOVED

Marked for deletion. It continues to take up memory until you execute flush().

DETACHED

Doctrine stops tracking it. This is the state you want in batch processes to reclaim memory. clear() and detach() are your primary tools for transitioning from MANAGED to DETACHED.

Hydration: The Bottleneck Almost Nobody Measures

Most developers measure performance solely by SQL execution time. Huge mistake.

In a real-world import process involving 5,000 entities and eager relationships, we measured this:

OperationTime
SQL50ms
Hydration600ms

Hydration is the process where Doctrine transforms raw rows into a full object graph: creating entities, casting and assigning values, generating proxies, registering everything in the Identity Map, creating snapshots, initializing collections, and so on.

It is far more expensive than it looks, especially when relationships are involved.

PDO vs. Doctrine ORM: A Fair Comparison

With PDO:

$rows = $pdo->query($sql)->fetchAll(); // Arrays planos

Low memory consumption. Fast. No magic.

With Doctrine:

$users = $query->getResult(); // Objetos + grafo completo

You get all the power of the ORM… alongside all of its overhead.

flush(): Much More Than Just Executing SQL

Before even touching the database, Doctrine performs:

  • computeChangeSets() across all managed entities
  • Cascading operations
  • Relationship synchronization
  • Lifecycle callbacks and listeners (preFlush, postFlush, etc.)

With 100 entities, it is unnoticeable. With 10,000, you begin to feel it. With hundreds of thousands, it can completely freeze your process.

The Memory-Destroying Pattern (That We’ve All Written)

foreach ($rows as $row) {
    $entity = transform($row);
    $entityManager->persist($entity); // ¡Acumulando todo!
}
$entityManager->flush(); // Demasiado tarde

Every persist() appends the entity, its snapshot, and references to the UnitOfWork. By the end, you have hundreds of thousands of objects in memory.

The Solution That Actually Works: Batches + clear()

$batchSize = 1000;

foreach ($rows as $i => $row) {
    $entity = transform($row);
    $entityManager->persist($entity);

    if (($i % $batchSize) === 0) {
        $entityManager->flush();
        $entityManager->clear();   // ← Esto es clave
    }
}

$entityManager->flush(); // Últimos registros

clear() flushes both the UnitOfWork and the entire Identity Map, detaching all entities. It is the single most effective way to keep memory under control in long-running processes.

Tip: Start with a batch size of 500–2000 and fine-tune it based on your environment.

toIterable(): The Right Way to Process Large Volumes

Instead of:

$users = $query->getResult(); // Todo en memoria

Use:

foreach ($query->toIterable() as $user) {
    process($user);

    if (($i % $batchSize) === 0) {
        $entityManager->clear();
    }
}

It hydrates entities progressively, keeping memory consumption flat.

The Hidden Cost of Relationships

Complex relationships compound the problem. For example:

User → Orders → Items → Products

A seemingly small query can end up hydrating:

  • Thousands of objects.
  • Proxies.
  • Collections.
  • Internal associations.

Hydration costs explode, especially with:

  • EAGER associations.
  • Massive joins.
  • Automatic serialization (API Platform, normalizers).

When Should You NOT Use Doctrine?

Doctrine is outstanding for:

  • Rich domain models
  • Complex business logic
  • Critical transactional operations

However, avoid it for:

Use CaseRecommended Alternative
Analytics / ReportingRaw SQL + DTOs
ETL / Massive ImportsDBAL or dedicated tooling
Large ExportstoIterable() + streaming
Dashboards / Heavy ReadsRead Models (CQRS) + optimized SQL

Rule of thumb: If you are only reading data and do not need the power of an ORM, do not use Doctrine.

Doctrine Is Powerful, but Costly

Doctrine does not consume memory without reason. It does so to sustain a sophisticated tracking, consistency, and relationship engine. Problems arise when we bring that heavy machinery into contexts where it is not needed.

Key techniques to avoid pain:

  1. Process in batches with flush() + clear()
  2. Use toIterable() for large queries
  3. Avoid findAll() and EAGER associations in bulk operations
  4. Pick the right tool for the job (not every problem is a nail for the Doctrine hammer)

Doctrine remains one of the best ORM tools in the PHP ecosystem when applied thoughtfully. The secret lies in understanding its real runtime costs and knowing when to turn off the magic.

Frequently Asked Questions

detach() or clear()?

  • clear(): Clears the entire EntityManager. Best suited for batch processing.
  • detach($entity): Detaches only a specific entity. Useful when you have reference entities you want to keep loaded.

Use clear() when processing in batches where nothing needs to be retained across iterations. Use detach() when keeping reference entities (such as configuration or catalog lookups) active across batches.

How does lazy loading affect memory?

Lazy loading delays relationship hydration until properties are accessed. This can:

  • Reduce initial memory usage (if relationships are never accessed).
  • Unexpectedly balloon memory (if many relationships are accessed later in the loop).

Solution: Use EAGER only when strictly required, or load associations explicitly via JOIN FETCH.

toIterable() or iterate()?

Both allow processing rows progressively, but toIterable() is the modern recommendation because it hydrates entities one by one and works seamlessly with clear() inside the loop. iterate(), the older API, has quirks with specific Doctrine setups and is deprecated in recent versions. Unless you are on a very old ORM release, always use toIterable().

What About You?

Have you run into severe memory issues with Doctrine? By how much did your flush() times improve after introducing batches and clear()? Let me know in the comments—especially if you encountered edge cases where these techniques were not enough.