Singleton Alternative - 它是等同的吗?

Wil*_*iam 2 c# performance singleton c#-4.0

快速提问 -

我知道标准单例模式如下:

原版的

public class Singleton1
{

    public static Singleton1 _Instance;
    public static Singleton1 Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = new Singleton1();
            }
            return _Instance;
        }
    }

    private Singleton1()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

但似乎这段代码是不必要的.对我来说,您可以使用以下任一简单设计模式完成相同的任务:

版本2

public class Singleton2
{
    public static readonly Singleton2 Instance = new Singleton2();

    private Singleton2()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

版本3

public class Singleton3
{
    static Singleton3()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

对我来说,似乎版本2是执行此操作的优越方法,因为它允许您传入参数(或不传递)但仍然具有有限数量的实例.我的应用程序对延迟/性能敏感 - 这些模式中的任何一种都有性能提升吗?

看起来虽然第一次访问每个人会更长,因为正在创建对象.此外,似乎原始的一个稍微慢一点,因为它必须检查每次其他访问它时它的支持字段是否为空.

提前致谢!

Pet*_*iss 7

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

快速,干净,线程安全.