Lazy Loading vs Eager Loading
What you'll learn: How to choose between loading related data on-demand versus loading everything upfront when working with ORMs.
When your objects have relationships (like a Customer with many Orders), you face a critical decision: load related data immediately or wait until it's actually needed?
Lazy Loading: Deferred Data Retrieval
Lazy loading delays fetching related objects until you explicitly access them. When you load a Customer, their Orders remain unloaded. Only when you call customer.orders does the ORM execute a separate query to retrieve them.
Analogy: Like a library card catalog. You don't pull every book when you enter the library—you fetch them only when needed.
Benefit: Saves resources when you don't need related data.
Danger: The N+1 query problem. If you loop through 100 customers and access their orders, you execute 1 query for customers + 100 queries for orders = 101 total queries. Performance disaster!
Eager Loading: All-at-Once Retrieval
Eager loading fetches related data upfront, typically using SQL JOINs or batched queries. When you load a Customer, their Orders come along immediately.
Benefit: Prevents N+1 queries by loading everything in one or few queries.
Danger: Loads data you might never use, wasting memory and bandwidth.
Choosing the Right Strategy
Use lazy loading as the default for simple cases where you rarely need related data. Switch to eager loading when you know you'll access relationships, especially in loops or list views. Modern ORMs let you explicitly specify: "load this customer and eagerly fetch their orders."
Key Takeaway: Lazy loading defers queries until needed but risks N+1 problems; eager loading prevents N+1 by loading related data upfront but may fetch unused data—choose based on your access patterns.