I have always known that loading multiple nodes at the same time is faster than loading them one by one.
What I wasn't aware of, is the huge performance difference between the two ways of loading nodes.
I made an example to see the difference. Here's my result:
Load 1000 nodes one by one:
$start_time = microtime(TRUE);
foreach (range(1, 1000) as $nid) {
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
if ($node) {
print_r($node->id());
}
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);
Execution time: 10.7266 seconds.
Load 1000 nodes at the same time:
$start_time = microtime(TRUE);
$nids = [];
foreach (range(1, 1000) as $nid) {
$nids[] = $nid;
}
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $node) {
if ($node) {
print_r($node->id());
}
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);
Execution time: 1.1664 second.
How can loadMultiple
be 9.2 times faster than loading the nodes one by one?
Is it the connection between Drupal and the database? What other factors are slowing down the process when loading the nodes one by one?
I have cleared the cache after every request to avoid the loaded nodes being cached.
I used the microtime
function to calculate the exact execution times.
drupal
because PHP experts that doesn't know anything about Drupal would think\Drupal::entityTypeManager()
that's definetely not a PHP function I know... So while it might be related to PHP code, I still think it's on topic here, because it's about some of Drupal's core functions and how they operate.foreach
always takes longer than loading one large chunk of data at once.