Create single allocations and instances of data in a singleton. Quickly review the singleton types, and look at an example of one of the fastest. You may also need to reset a singleton's data, and we look at layouts that allow that. Augment Jon Skeet's extremely thorough singleton implementation page.
The singleton design pattern is an interface that allows a class to enforce that it is only allocated (instantiated) once. It is the same in every language, but here we look at resources about it in C#. What follows is one of the best implementations of singleton. (It is based on code from the page linked above.)
/// <summary>
/// Declare and implement the site structure.
/// </summary>
public sealed class SiteStructure
{
/// <summary>
/// The singleton instance.
/// </summary>
static readonly SiteStructure _instance = new SiteStructure();
/// <summary>
/// Get an instance of the structure singleton.
/// </summary>
public static SiteStructure Instance
{
get
{
// Fastest solution that avoids null check and is thread-safe
// because of readonly keyword.
return _instance;
}
}
// [omitted] data members and methods.
/// <summary>
/// Run initialization on the singleton.
/// </summary>
private SiteStructure()
{
Initialize();
}
private void Initialize()
{
// [omitted] generate data.
}
}
Because the _instance member is created directly in its declaration. FxCop warns when you initialize a static member in a static constructor because it is slower. This version is faster than others because the property Instance does no null checking.
Ten times faster than the version that does a null check. (For the version of singleton I call 'naive', I add null checks and lazily instantiate the structure.) For visual effect, I have a chart that compares 100 million access of each type of singleton. The times are 435 ms and 42 ms.
Provide a new instance method called Reset(). Then, call the Initialize method in code like that in this article. This effectively will run the private constructor again by an outside request. I have found resetting singletons very useful, if some data changes or if I am debugging something. The reset method might look like this.
/// <summary>
/// Reset the singleton so that changes to the XML will be picked up when
/// running in the debugger.
/// </summary>
public void Reset()
{
Initialize();
}
Full credit for the singleton (approach) here goes to Jon Skeet. Singletons are critical to our applications, and since they are used so frequently, making them 10 times faster and thread-safe is a very important improvement. Finally, I took additional benchmarks to improve the singleton presented here.