Bookmark and Share

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 that 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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.