Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Lazy Loading really bad?

I hear a lot about performance problems about lazy loading, no matter if at NHibernate, Linq....

The problem is N+1 selects. Example, I want all posts and its users, at foreach I lazy Load Users, them I need one select for posts, plus N select for each user.

Lazy Loading:

1 - select ....from post
N - select ....from user

The "good" approach is do a join:

1 - select .....from post inner join user on post.UserId = user.Id

But seeing EF generated SQL, I realized that a lot of data is wasted. Imagine that all posts are the same User. Inner Join will bring all users columns for each post row.

In performance, which approach is best?

like image 307
Felipe Pessoto Avatar asked Jan 28 '10 14:01

Felipe Pessoto


People also ask

Is lazy loading good for performance?

The benefits of lazy loading include: Reduces initial load time – Lazy loading a webpage reduces page weight, allowing for a quicker page load time. Bandwidth conservation – Lazy loading conserves bandwidth by delivering content to users only if it's requested.

Should I lazy load everything?

It may be tempting to lazy-load every single media resource on the page with JavaScript, but you need to resist this temptation. Anything resting above the fold shouldn't be lazy-loaded. Such resources should be considered critical assets, and thus should be loaded normally.

How do I stop lazy loading?

To disable lazy loading on a specific post or page, open the post or page, and in the “Cache Options” meta box, un-check the “LazyLoad for images” option. Don't forget to publish or update the post or page to save your changes.


1 Answers

Lazy loading is neither good nor bad. See this for a more lengthy explanation:

When should one avoid using NHibernate's lazy-loading feature?

In general, lazy loading is a good default behavior for an ORM, but as an ORM user you need to be conscious of when to override the default and load data eagerly. Profiling the performance of your application is the best way to make decisions about using lazy loading or not using it. Be wary of spending too much effort on premature optimization.

like image 75
Michael Maddox Avatar answered Oct 04 '22 00:10

Michael Maddox