Welcome to my blog, stay tunned :
Home | Blogs | Stephane Eyskens's blog

Leveraging .NET 4 in SharePoint 2013 Series (2) - Lazy Loading

I'll be writing a series of blog posts about leveraging .NET 4 within SharePoint 2013. As you might know already, SharePoint 2013 is now based on this .NET runtime version v4.0.30319 which actually allows developers to benefit from .NET 4 features. You couldn't do that with SharePoint 2010 which was still based on .NET runtime v2.0.50727.

Lazy Loading

Lazy Loading in .NET 4 allows to defer the instantitiation on an object until it is actually being used. It can be particularly useful in scenarios involving heavy objects consuming a lof of resources.

Say you want to gather all the property bags of all the SharePoint webs within a site collection in order to build an in-memory objects that you will query afterwards instead of keeping instantiating webs. The code of collecting the information could look like this:


public class AllWebProperties
{
        
    private List<Tuple<string, string, string>> _Properties = new List<Tuple<string,string,string>>();
    public AllWebProperties()
    {
        Console.WriteLine("Inside the contructor at {0}", DateTime.Now);
        using (SPSite Site = new SPSite("http://sp2013"))
        {
            foreach (SPWeb Web in Site.AllWebs)
            {
                foreach (DictionaryEntry Property in Web.Properties)
                {
                    _Properties.Add(
                        new Tuple<string, string, string>(
                            Web.Url,
                            Property.Key as string,
                            (Property.Value != null) ? Property.Value as string : String.Empty));                       
                }
                Web.Dispose();
            }
        }
    }
        
    public  List<Tuple<string, string, string>> Properties
    {
        get
        {
            return _Properties;
        }
    }
       
}

Say now you instantiate the object and start calling its properties & methods:

class Program
{


    static void Main(string[] args)
    {
        Lazy<AllWebProperties> Instance = new Lazy<AllWebProperties>();
        Console.WriteLine("Instance created at {0}",DateTime.Now);
        Thread.Sleep(2000);            
        Console.WriteLine(Instance.Value.Properties.Count);        
        Console.WriteLine("Finished processing at {0}",DateTime.Now);    
        Console.Read();
    }        
      
}

As you can see, between the instantiation of the lazy object and the effective call to the constructor, 2 seconds elapsed because the AllWebProperties object was effectively instantiated when Instance.Value is called. Combining that to a singleton pattern can also ensure that you will have one heavy running instance of your object that will really be loaded in memory when an explicit call to a property/method is requested.

Happy Coding!