Reputation: 5259
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 = "";
}
Upvotes: 0
Views: 71
Reputation: 125610
??
inside your Instance
property is pointless, because you initialize underlying field before.
You should not be worried about performance here, JIT compiler will most likely optimize it anyway.
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.
Upvotes: 4
Reputation: 6366
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.
Upvotes: 2