- Home /
Which one is faster? (Cache related)
Hi,
Which one is faster, store a reference to a class or add a static field and make it Singleton?
Thanks
Answer by Landern · Feb 04, 2015 at 02:29 PM
A reference to an object and a static member are not equatable other than a static class member COULD contain a reference to an object that can be access through that class member that exists once and is accessed through the class, rather than the instance member which is scoped in the scope in which it's instantiated and set on other objects.
The static class member exists across the board. Also a static member is not equatable to a singleton which is a design pattern that reinforces the existence of an instance of an object and access through a static class member...
Your implementation(mileage) will of course be different.
Example:
// Just a static class member that exists across the board on all Bucket's and references the same memory location, setting anywhere affects all references to it since it only exists as the one and only score member on the class Bucket.
public class Bucket
{
public static int score = 0;
}
// usage of just the static
public int GetScore()
{
return Bucket.score;
}
// Singletonish
public class SingleBucket
{
private BucketProperties bucketProps = null;
private SingleBucket()
{ }
public static BucketProperties BucketInstance
{
get
{
if ( bucketProps == null)
bucketProps = new BucketProperties();
return bucketProps;
}
}
}
public class BucketProperties
{
public int score = 0;
}
// usage of singleton in some method in some class
public int GetScore
{
return SingleBucket.BucketInstance.Score;
}
Either way you do it, if you're setting references at any point(not the int example but say a concrete type you make) then at some point you will have to get that reference, and that shouldn't different much when it comes to speed. The accessibility is a it different then just a plan static member on a class that has class members and instance members.
Your answer

Follow this Question
Related Questions
Is holding a reference to the Coroutine returned by StartCoroutine necessary? 1 Answer
Can't load objects from asset bundle when using AssetBundle.CreateFromFile 1 Answer
"Caching" code in the Start() to run it "later" 3 Answers
I cannot delete Unity cache 0 Answers
C# - can I cache a GameObject script component in another script? 1 Answer