PROWAREtech
.NET: Lazy Load Data
Lazy loading is a design pattern commonly used to defer initialization of an object until the point at which it is needed. This can improve performance, reduce system overhead, and ensure efficient use of resources. Lazy loading is especially useful when dealing with large objects or resources whose creation is computationally expensive.
Using Lazy<T> Class
The .NET Framework provides a convenient way to implement lazy loading through the Lazy<T>
class. Here’s how to use it:
Define the
Lazy<T>
Instance: Define aLazy<T>
variable whereT
is the type of object to lazily initialize.Initialization Logic: Pass a delegate to the constructor of
Lazy<T>
that contains the initialization logic of the object.Access the Value: Access the object through the
Value
property of theLazy<T>
instance. The instance will be created at this point if it hasn't been already.
using System;
class BigSlowResource
{
public BigSlowResource()
{
Console.WriteLine("BigSlowResource created!");
}
public void Operate()
{
Console.WriteLine("Operating!");
}
}
class Program
{
static void Main()
{
Lazy<BigSlowResource> lazyResource = new Lazy<BigSlowResource>(() => new BigSlowResource());
Console.WriteLine("Lazy object created, resource not initialized yet.");
// The BigSlowResource object is created when accessing the Value property.
lazyResource.Value.Operate();
}
}
Or:
// NOTE: incompatible with .NET Core 3.1
using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
private static readonly Lazy<List<string>?> LazyListOfStrings = new(LoadListFromJson);
private static List<string>? LoadListFromJson()
{
string json = "[\"1\",\"2\"]";
return JsonSerializer.Deserialize<List<string>>(json);
}
static void Main()
{
foreach(var s in LazyListOfStrings.Value)
Console.WriteLine(s);
}
}
Custom Lazy Loading
If wanting more control over the initialization logic or if not working in an environment where Lazy<T>
is available, implement lazy loading manually:
class BigData
{
private BigResource _resource;
public BigResourceResource
{
get
{
if (_resource == null)
{
_resource = new BigResource();
}
return _resource;
}
}
}