Wednesday, October 01, 2008 #

Lazy Loading Properties

What do you do when you are loading hundreds of objects and it's taking too long? When you instantiate the object in a vacuum, it runs very fast. However, you run a few tests and determine a collection on the object causes a bottleneck if a call to load the collection occurs many times in succession.

    public class Customer
    {
        
private List<Account> accounts = SlowLoadMethod();

        
public IList<Account> Accounts
        {
            
get{ return accounts; }
        }

        ...
    }

If the property doesn't need to be accessed immediately upon instantiation, we can use a technique called lazy loading. This means the data isn't loaded into the member variable and the call to the slow method will not occur until the first time the property is accessed. This is easy to accomplish via a conditional check inside the property's get accessor.

    public class Customer
    {
        
private List<Account> accounts;

        
public IList<Account> Accounts
        {
            
get
            {
                
if (accounts == null)
                {
                    accounts = SlowLoadMethod();
                }

                
return accounts;
            }
        }

        ...
    }

In this example, the accounts private member is null until the first time someone accesses the Accounts property. At that point, the accounts private member is assigned a value from the SlowLoadMethod. Subsequent accesses to the Accounts property skip this step and returns the field as usual.

posted @ Wednesday, October 01, 2008 5:56 PM | Feedback (0)