简体   繁体   English

调用多个单例实例

[英]Calling Multiple Singleton Instances

I have a singleton class like this one 我有一个这样的单身人士班

class Singleton
{
    private static Singleton _instance = new Singleton();
    public string Username { get; set; }
    public string Password { get; set; }

    public static Singleton Instance
    {
        get { return _instance ?? (_instance = new Singleton()); }
    }
}

Does it impact performance in anyways when calling Singleton.Instance.X multiple times like this 像这样多次调用Singleton.Instance.X时,它是否仍然会影响性能?

private void Method()
{
    Singleton.Instance.Username = "";
    Singleton.Instance.Password = "";
}

or this is better (& why) 或者这更好(&为什么)

private void Method()
{
    Singleton singletoon = Singleton.Instance;
    singletoon.Username = "";
    singletoon.Password = "";
}
  1. ?? inside your Instance property is pointless, because you initialize underlying field before. Instance属性中的内容是没有意义的,因为您之前初始化了基础字段。

  2. You should not be worried about performance here, JIT compiler will most likely optimize it anyway. 您不必担心性能,JIT编译器很可能会对其进行优化。

  3. The whole case looks like premature optimization. 整个情况看起来像过早的优化。 Have you really experience problems with your current code? 您当前的代码真的遇到问题了吗?

Update 更新资料

To answer the question asked in comments: 要回答评论中提出的问题:

I would go with 我会去

private void Method()
{
    Singleton singletoon = Singleton.Instance;
    singletoon.Username = "";
    singletoon.Password = "";
}

but not because of performance, but because it's easier to read. 但这不是因为性能,而是因为它更易于阅读。

This approach: 这种方法:

private void Method()
{
    Singleton singletoon = Singleton.Instance;
    singletoon.Username = "";
    singletoon.Password = "";
}

Is better beacuse you do not execute the if-statement inside your getter. 最好是因为您不在getter中执行if语句。

In this case: 在这种情况下:

private void Method()
{
    Singleton.Instance.Username = "";
    Singleton.Instance.Password = "";
}

You call getter twice, so the if-condition (represented in your case by '??'). 您两次调用getter,因此使用if条件(在您的情况下以'??'表示)。

Although the difference in performance is really slight , especially in your scenario. 尽管性能差异确实很小 ,尤其是在您的情况下。

Btw you are anyway initiliazing your Singleton _instance statically so there is no need to do this inside your getter. 顺便说一句,无论如何,您都是静态地初始化Singleton _instance因此不需要在吸气器中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM