Skip to main content

How to loop through many nodes without hitting memory limits

Posted on March 18, 2022


Clear internal entity cache on each iteration to avoid hitting memory limits.

$nids = \Drupal::entityQuery('node')
         ->condition('type', 'article')
         ->execute();

foreach ($nids as $nid) {
    // Load and use node for something here.
    $node = \Drupal\node\Entity\Node::load($nid);

    // Clear entity memory cache before moving to next node.
    \Drupal::service('entity.memory_cache')->deleteAll();
}