Tuesday, November 22, 2011

lazy loading versus eager fetching in NHibernate

I was surprised to learn that a method such as this one might invoke a trip to the database to find a program for a program plan!

public string Foo(ProgramPlan bar)

{

   return bar.Program.Name;

}

 
 

Why? NHibernate may be set to lazy load objects, getting just the objects and not their children. The properties on the object that would otherwise govern the children will instead contain proxy objects which fire off calls to your database to get what they need if someone pokes at them (but will be quiet and harmless otherwise).

Why lazy load? In the opposite scenario in which one eagerly fetches everything downstream of an object one could be pulling back and ignoramus swath of concerns. For example: if you eager load a foo and the foo has a collection of bars attached to it and each bar has a collection of bazes and each baz has a collection of quxes... well, without sounding too much like Doctor Seuss I think you can see the performance problem of getting everything when you may not really need it.

 
 

As I was going to St Ives

I met a man with seven wives

Every wife had seven sacks

Every sack had seven cats

Every cat had seven kittens

Kittens, cats, sacks, wives

How many were going to St Ives?

No comments:

Post a Comment