Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using Lazy<T> bad for performance?

Recently I was having some issues with a singelton class that was lazy initializing a dictionary where a second thread would try to use it before it had actually been populated. So I implemented the variable initialization through the Lazy<T> class.

Here is my code:

private static Dictionary<string, string> GroupDefaults
{
    get { return mGroupDefaults.Value; }
}
private static Lazy<Dictionary<string, string>> mGroupDefaults =
    new Lazy<Dictionary<string,string>>(delegate
    {
        Dictionary<string, string> defaults = new Dictionary<string, string>();
        foreach (KeyValuePair<string, UnitGroup> groupDef in Groups)
            defaults.Add(groupDef.Key, groupDef.Value.First().Key);
        return defaults;
    });

This fixed the problem and now I am considering making this a regular practice of mine to use the Lazy<T> class anywhere I do lazy initialization to avoid any possible threading issues. So basically I would like to know if this is good/common practice? Or will it be detremental to performance or something?

like image 724
Alex Hope O'Connor Avatar asked Jun 28 '12 01:06

Alex Hope O'Connor


2 Answers

From the documentation, I find the following:

If no delegate is passed in the Lazy constructor, the wrapped type is created by using Activator.CreateInstance when the value property is first accessed. If the type does not have a default constructor, a run-time exception is thrown.

Activator.CreateInstance is a method that is notoriously bad for performance. However, that doesn't seem to be a problem in your case, and at any rate, as dlev said, invoking the method once wouldn't be a problem. I haven't seen Lazy<T> used very often, but I do not see any reason not to use it in your case.

like image 198
GregRos Avatar answered Oct 06 '22 01:10

GregRos


It's pretty hard to say without knowing what type of performance constraints you have, but in my experience, one-time initialization is rarely a bottleneck (since by definition it only occurs once.) Lazy<T> was written to provide you with this exact service, so I would recommend using it.

like image 39
dlev Avatar answered Oct 05 '22 23:10

dlev