views:

478

answers:

4

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 collums for each post row.

In performance, which approach is best?

+6  A: 

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

http://stackoverflow.com/questions/1682165/when-should-one-avoid-using-nhibernates-lazy-loading-feature/1686795#1686795

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.

Michael Maddox
+1 for a shameless plug <g>
Lieven
I think the general rule is DBA's don't like it and web application developers do :)
Aim Kai
+1  A: 

There's no bad and good for lazy loading. You have to decide if you prefer to load resources on run time or application loading times. For example - Real time usually uses a buffer to avoid allocating resources on runtime. That's the opposite of lazy loading and is beneficial for Real Time software.

Lazy loading is beneficial if you have an application that runs for long duration and you don't want to allocate resources on startup.

Ben
+3  A: 

The issue with Lazy Loading is being aware of what it is and when it can bite you. You need to be aware of how many potential trips could be made to the database, and how to work around that. I don't view LL as being bad. I just need to be aware of the ramifications of it.

Randy Minder
+2  A: 

Most of my applications involve a service boundary (web service, WCF, etc) and at that point lazy loading at the OR/M is pointless, and implementing lazy loading in your entities that sit on top of your service is kind of a bad idea (the entities now must know about the service).

Bryan Batchelder