Lazy loading, also known as deferred instantiation or initialization, delays object creation until the object is actually needed. This approach imprvoes application performance by avoiding unnecessary computations and memory usage.
In .NET Framework 4.0, the Lazy<T> class simplifies lazy loading implementation. Here's a basic example:
// Creates a lazily-loaded string object
Lazy<string> s = new Lazy<string>(TestLazy.GetString);
Console.WriteLine(s.IsValueCreated); // False
Console.WriteLine(s.Value); // Current value
Console.WriteLine(s.IsValueCreated); // True
public class TestLazy
{
public static string GetString()
{
return DateTime.Now.ToLongTimeString();
}
}
The IsValueCreated property checks if the object has been instantiated, while Value retrieves the current object.
For more complex scenarios, consider lazy loading child objects:
public class BlogUser
{
public int Id { get; private set; }
public Lazy<List<Article>> Articles { get; private set; }
public BlogUser(int id)
{
this.Id = id;
Articles = new Lazy<List<Article>>(() => ArticleServices.GetArticlesByID(id));
}
}
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime PublishDate { get; set; }
}
public class ArticleServices
{
public static List<Article> GetArticlesByID(int blogUserID)
{
return new List<Article>
{
new Article{Id=1, Title="Lazy Load", PublishDate=DateTime.Parse("2011-4-20")},
new Article{Id=2, Title="Delegate", PublishDate=DateTime.Parse("2011-4-21")}
};
}
}
Lazy loading is particularly useful when:
- Creating child objects is resource-intensive
- Child objects might not be needed during program execution
- Application startup requires creating many objects, but only few are immediately necessary