I'm running a long drush script and its causing memory problems.

Then I tried debbuging it and I have this very simple code:

$query = \Drupal::entityTypeManager()->getStorage('user');

foreach ($emails as $i => $email) {
    $users = $query->loadByProperties(['mail' => $email]);
    $user = reset($users);


When I ran the script I noticed that the memory increases dramatically as the script is running. What is causing this memory issue?


1 Answer 1


The memory issue is caused by the internal entity cache which you can release by using $storage->resetCache().

You've named the user storage $query, so replace the unset() commands with:


Recently core added the advice to use the entity.memory_cache service instead, to only clear the in-memory cache and not invalidate the entities in the database:


This is more efficient, in your script and also for subsequent loads of the entities.

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21ContentEntityStorageBase.php/function/ContentEntityStorageBase%3A%3AresetCache/9.2.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.