The Case for Lazy Instantiation

Assume that we create some large data item in an object, e.g. the listofAllFamousDogs object in the sample below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Dog
{
    public string Name { get; set; }
 
    public Dog(string name)
    {
        Name = name;
    }
 
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
 
    private static List<Dog> listOfAllFamousDogs = GenerateBigListOfFamousDogs();
 
    private static List<Dog> GenerateBigListOfFamousDogs()
    {
        Console.WriteLine("Loading big list of famous dogs!");
        List<Dog> bigList = new List<Dog>();
        <span class="skimlinks-unlinked">bigList.Add(new</span> Dog("Lassie"));
        <span class="skimlinks-unlinked">bigList.Add(new</span> Dog("Rin Tin Tin"));
        // load 1,000 more dogs here
 
        return bigList;
    }
 
    public bool IsFamous
    {
        get { return listOfAllFamousDogs.Contains(this); }
    }
}
The problem with this is that we end up creating the big list when we first use the class–whether or not we’ll later use the IsFamous property.
1
2
Dog bob = new Dog("Bob");
<span class="skimlinks-unlinked">bob.Bark</span>();


942-001
What we need is to lazily instantiate this list.  That is–wait to create the list until we actually need it.