We’re having some performance issues with our Application at work. We have this one gigantic business object that just needs help in terms of performance.
One of the improvements that I added is implementing “Lazy Instantiation”. Technically, this is old news and I know I use to do it in a very old-fashioned way, where you have a private backing field, check the null ,you handle your own thread and blah..blah..blah.
Before I started playing with the .Net 4.0 Lazy, let us refresh our memory… what is lazy instantiation?
“ … to defer the creation of a large or resource-intensive object , particularly when such creation might not occur during the lifetime of the program“
The built-in Lazy function in .NET 4.0 has a lot to offer, handles the basic lazy loading up to your threading.
See below for more detailed description or go to this link.

In the code below, you will see that your getter in the Employees property is a lot cleaner than how we used to do lazy loading.
<pre>internal class Employers
{
private readonly Lazy<List<Employee>> mLazyEmployees;
public Employers()
{
mLazyEmployees = new Lazy<List<Employee>>(GetEmployees, LazyThreadSafetyMode.None);
if (!mLazyEmployees.IsValueCreated)
{
Console.WriteLine("-->Employee list is not initialized yet<--");
}
}
public string Name { get; set; }
public List<Employee> Employees
{
get
{
return mLazyEmployees.Value;
}
}
public string Description { get; set; }
private List<Employee> GetEmployees()
{
var employees = new List<Employee>();
for (var i = 0; i < 5; i++)
{
var e = new Employee { Name = "Emp"+i.ToString(), JobTitle = "CEO" +i.ToString() , Salary = 10000+i };
employees.Add(e);
}
return employees;
}
}</pre>
In main, you will see that even though we created the Employer object right away the “employees” is not created yet – this is the effect of using the Lazy. We are pretty much saying “hey, don’t create me until you really need me at that moment in time”
<pre> static void Main()
{
Console.WriteLine("Calling and initializing Employers; the Employees is not created yet ");
Console.WriteLine();
var emp = new Employers
{
Name = "CrackTheCode LLC",
Description = "Team of people that writes the code and make it right the FIRST time."
};
Console.WriteLine();
Console.WriteLine(emp.Name);
Console.WriteLine(emp.Description);
Console.WriteLine("*** Here I want to call my employee list now");
Console.WriteLine("*** and this will be the only time that you will create the emp.Employees");
foreach (var ee in emp.Employees)
{
Console.WriteLine(ee.Name + " - " + ee.JobTitle + " - " + ee.Salary.ToString());
}
Console.ReadLine();
}</pre>
Check the output below.

LazyOutput
I know in coding approach, most often than not it’s a preference issue. Reasons why I want to head this way are the following:
- Cleaner look in your getter
- Threading is supported
… why work harder if someone is willing to do the hard part for you?