How do I make entity reference lookup faster I am trying to look up entity reference id's for each node so I can do stuff with them.

$all_nodes = db_select('node','e')-&gt;fields('e',array('nid','type'));
$all_nodes-&gt;addField('e','nid');
$all_nodes-&gt;condition('type','author');
$data = $all_nodes-&gt;execute();
$the_result = $data-&gt;fetchAll(\PDO::FETCH_ASSOC);

foreach ($the_result as $node){
     $node_load =  \Drupal\node\Entity\Node::load($node['nid']);
     foreach ($node_load-&gt;field_institution_with_date as $item) {
        $the_entity_id = $item-&gt;entity-&gt;id();
     }
}


Any idea on how to optimize this? it seems that $item-&gt;entity-&gt;id(); is the bottleneck and it is taking several seconds to iterate through about 1000 nodes.
Ideally you'd use an Entity Query for this, but in principle:


You can batch load the parent nodes

...
$nids = $data-&gt;fetchCol();

foreach (Node::loadMultiple($nids) as $node) {


If memory is a concern with thousands of nodes, just implement some simple php logic around the loop to batch it into, say, 50-100 at a time.
If you don't need the child entities, just their IDs, they're available without a DB hit

foreach ($node_load-&gt;field_institution_with_date as $item) {
    $the_entity_id = $item-&gt;target_id;


If you do need the entities, you could build an array of all IDs using this method, and batch load those using Node::loadMultiple after the outer loop.