Eager Loading vs Lazy Loading: Which One Is Faster?
You have a User. A User has Orders. Each Order has Items. When you load a User, should you also load their Orders and Items?
The answer depends on whether you are going to use them. If yes, load everything now (eager loading). If no, load them later when needed (lazy loading). Getting this wrong is the number one cause of ORM performance problems.
Key sources: "High-Performance Java Persistence" by Vlad Mihalcea, Hibernate documentation, Martin Fowler's Patterns of Enterprise Application Architecture.
Eager Loading
Load everything at once. One database query that joins all the related tables.
Good when you will definitely use the related data. A user profile page that always shows recent orders.
Bad when you load data you do not need. Loading 500 users with their orders just to show a name list wastes resources.
Lazy Loading
Load on demand. Only the main entity is fetched initially. Related data loads only when accessed.
Good when you might not need the related data. A list of users where only names are displayed.
Bad when you always need the data. Loading each user's orders one-by-one triggers the N+1 problem.
The N+1 Problem
The most common performance bug in ORM applications. Loading 100 users triggers 1 query for all users plus 100 queries for their orders. The database connection pool cannot handle that load.
Fix it with: JOIN FETCH, @EntityGraph, or batch fetching.
Key Takeaways
- Eager loading loads everything now. Good when you will use it. Bad when you will not.
- Lazy loading loads on demand. Good for memory. Poor performance with N+1 if misused.
- The N+1 problem is the top ORM performance killer. Detect it with SQL logging.
- Best practice: default to lazy, use JOIN FETCH for specific needs.