Lazy loading - what's the best approach?

Tim Peel picture Tim Peel · Feb 7, 2009 · Viewed 7.3k times · Source

I have seen numerous examples of lazy loading - what's your choice?

Given a model class for example:

public class Person
{
    private IList<Child> _children;
    public IList<Child> Children
    {
        get {
            if (_children == null)
                LoadChildren();
            return _children;
        }
    }
}

The Person class should not know anything about how it's children are loaded .... or should it? Surely it should control when properties are populated, or not?

Would you have a repository that couples a Person together with its children collection or would you use a different approach, such as using a lazyload class - even then, I don't want a lazyload class blurring in my model architecture.

How would you handle performance if first requesting a Person and then its Children (i.e. not lazy loading in this instance) or somehow lazy loading.

Does all this boil down to personal choice?

Answer

krosenvold picture krosenvold · Feb 7, 2009

The best lazy loading is avoiding it ;) Thread safety is an immediate problem you'll have to handle. I have no count of how often I have seen production systems with 8 cpu cores run lazy loading 8 times for every single lazy loading pattern in use. At least on server startups all server cores have a tendency to end up in the same places.

Let a DI framework construct it for you instead, if you can. And if you cannot, I still prefer explicit construction. So all sorts of AOP magic simply do not cut it with me, go for explicit construction outside the class. Don't put it inside the person class, just make a service that constructs the objects in the proper manner.

Introducing "magic" layers that more or less transparently do these things seem like a nice idea, but I have yet to come across implementations that do not have unforseen and problematic consequences.