What is Lazy Loading and Eager Loading?

Asked

Viewed 5,412 times

26

  • What is Lazy Loading and Eager Loading?

I saw these terms in a documentation, but I did not understand it very well, so my doubt is what these terms mean and I would like, if possible, to restrict the scope of the answer/question to PHP and CakePHP (MVC framework with built-in ORM), because they are the technologies where I am having the most contact lately and where I saw the terms.

  • The Laravel 4 also uses the so-called Eager Loading Constrains

  • Is it language or PHP independent? I got confused :P

  • @jbueno independent, put PHP only for example.

2 answers

22


Eager Loading

It is the Load where all related classes are loaded in the same query. The ORM, usually through Joins, will bring all related entities.

Example of use

You have an entity List, where she has several entities Item (one to Many), in its entity List there is an attribute with a Collection of Items.

When you run a Find() or some command to bring these objects all their relations are loaded immediately, ie in your List will already be loaded in memory all your Items (in this example).

Therefore, these objects can already be referenced.

In certain cases the Eager loading becomes unnecessary, because not always when loading an entity you wish to have loaded in memory the related entities.

Example of load with Eager loading of Items related to List:

// Usando em conjunto com o find()
$query = $listas->find('all', ['contain' => ['Items']]);

// Como um método query no objeto
$query = $listas->find('all');
$query->contain(['Items']);

Note that more than one relation with contain can be defined

Lazy Loading

as its name says, it is a lazy load, when you perform a query by a certain entity your relations are not loaded in memory by the initial query, however, when executing some method that calls these records, another query will be executed to complete these related entities.

Example

Following the example of Lists and the related entity Item, if you used for example a Getitems() method from List, the ORM would execute a query and upload those entities to you.

Loads in Cakephp

According to Cakephp’s documentation Lazy Loading should be implemented by you, i.e., the ORM will not do this automatically.

Example of use

In this example the relations List x Item are manually loaded into the entity List.

 namespace App\Model\Entity;

 use Cake\ORM\Entity;
 use Cake\ORM\TableRegistry;

class Lista extends Entity
{

    protected function _getItems()
    {
        $items = TableRegistry::get('Items');
        return $items->find('all')
            ->where(['lista_id' => $this->id])
            ->toArray();
    }

}


Documentation Eager X Lazy Cakephp: http://book.cakephp.org/3.0/en/orm/entities.html#Lazy-loading-Associations

8

A classic example of this in PHP would be given with Laravel.

For example:

If we have a User model that relates to multiple Purchases, we could access these purchases like this

$usuarios = Usuario::all();

foreach($usuarios as $usuario)

    foreach($usuario->compras as $compra)
        echo "ID DA COMPRA é " . $compra->id

However, when doing this, for each iteration, a new query would be made in the purchase table, to relate to the user in which information is required of what purchases he has.

Imagine if you have 100 users on one system and each is linked to 20 purchases?

This would add up to 20,000 (twenty thousand) queries executed!

This, in Laravel 4, would be circumvented as follows:

Usuario::with('compras')->all();

So instead of 50 queries executed, you would have only two queries executed!

The last example would be this Eager Load!

Look at the question I asked about this in Performance of the Eloquent in the Laravel

  • "That would add up to 20,000 (twenty thousand) queries executed!" Actually you are misinterpreting, because queries are executed with joins and a query can return more than one record at a time

  • No I’m not, Fernando. I’ve done tests. In Laravel is not used JOINS. I’m talking about something I’ve already proven

  • If you use the Laravel relationship without the function with, for each interaction it does a query. Yes! It does not use a SELECT for each table (represented by the model). Example Usuario[1, 2, 3], SELECT * FROM compras where usuario_id = 1. And so, for each of the three.

  • 1

    I get it, I’m sorry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.