What is Lazy Loading and Eager Loading?

19

What is Lazy Loading and Eager Loading ? I saw these terms in a documentation but I do not quite understand it, so mine is to know what these terms mean and I would like to if possible restrict the scope of the answer / question to PHP and CakePHP (Framework MVC with ORM built in) since they are the technologies where I've been having the most contact lately and where I've seen the terms.

    
asked by anonymous 20.07.2015 / 14:59

2 answers

17

Eager Loading

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

Usage example

You have a List entity, where it has multiple Item entities, in its List entity there is an attribute with a Collection of Items .

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

So these objects can already be referenced.

In some cases Eager loading becomes unnecessary, because when you load an entity, you do not always want to load related entities into memory.

Example of load with Eager loading 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 relationship can be defined with contain

Lazy Loading

As the name itself says, it is a lazy load, when you run a query by a certain Entity your relationships are not loaded into memory by the initial query, however, when you execute some method that calls those records, another query to populate these related entities.

Example

Following the Lists example and the related entity Item , if you used for example a GetItems () method of List , the ORM execute a query and load those entities for you.

Loads in CakePHP

According to the CakePHP documentation Lazy Loading should be implemented by you, ie ORM will not do this automatically.

Usage example

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

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

}


Eager X Lazy CakePHP Documentation: link

    
20.07.2015 / 15:27
5

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

For example:

If we have a User model that relates to various Purchases, we could access such purchases

$usuarios = Usuario::all();

foreach($usuarios as $usuario)

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

However, in 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 on which purchases he has.

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

That would amount to 20,000 (twenty thousand) queries executed!

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

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

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

The last example would be that of Eager Load!

See the question I asked about this in Eloquent performance in Laravel

    
20.07.2015 / 15:41