Memory leak when looping through nodes I've got code that loops through nodes in order to generate processed output.

I've previously done an entity query that provided an array of node IDs. My main loop code looks like this:

foreach ($this-&gt;nids as $nid) {
    $node = Node::load($nid);
    $nodeData = $node-&gt;toArray();
    $nodeURL = $propertyNode-&gt;toUrl()-&gt;toString();
    print "Mem usage: ".memory_get_usage(true)."\n&lt;br&gt;";
}


Obviously, the loop shown here is a minimal example to demonstrate the problem; as it stands, it's pretty useless as it doesn't do anything with the data it loads.

However despite this, the loop is eating memory. The debug call to memory_get_usage(true) in the loop gives a bigger number every time, until the script eventually runs out of memory if I feed it enough nodes (about 300 seems to be enough to kill it).

Obviously, I can increase the memory available, but I'm reluctant to do that because I can't seee why the loop would be leaking memory in the first place.

Can anyone please explain why this fairly basic loop is causing a memory leak, and what I can do to prevent it?

A few additional notes:

I've tried adding unset() at the end of the loop to clear the node and data variables; this doesn't have any effect (I wasn't expecting it to, but I tried it anyway).

The nodes in question have about fifty custom fields, including a couple that are paragraphs, which in turn have fields of their own.

My real code passes the node data to a processor class that reformats it for use elsewhere. It builds an array of these objects, but they aren't the cause of the memory leak, hence why I've excluded them from the example code.

I'm currently running on Drupal 8.6; haven't had a chance to look at the 8.7 release from yesterday yet.
With thanks to the comments made by various people above, I have now optimised this code so that it doesn't run out of memory.

$chunks = array_chunk($this-&gt;nids, 100);

foreach ($chunks as $chunk) {
    $nodes = Node::loadMultiple($chunk);

    foreach ($nodes as $node) {
        //do stuff with the node here...
    }
    Drupal::entityTypeManager()-&gt;getStorage('node')-&gt;resetCache([$chunk]);
    print "Mem usage: ".memory_get_usage(true)."\n&lt;br&gt;";
}


I couldn't simply do loadMultiple for all the nodes at once as it was still using unholy amounts of memory, but chunking it and resetting the cache after each chunk seems to work nicely.

I experimented with different sized chunks, and I found I got the best mix of performance vs memory usage with the chunk size at 100. YMMV.