How to loop through many nodes without hitting memory limits

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