简体   繁体   中英

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

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.

  2. You should not be worried about performance here, JIT compiler will most likely optimize it anyway.

  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.

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 '??').

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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