- Home /
Efficiency of static properties
While I was implementing a class for mixing colors I started creating a list of properties defining key colors I wanted to use in the same way they are done in Unity's Color struct:
struct BubbleColor {
public enum Name { white, red, orange, yellow, green, blue, purple, brown };
public Name name;
public Color color;
private BubbleColor(Name name, Color color)
{
this.name = name;
this.color = color;
}
// I'm only putting a couple of colors to show how it's done
public static BubbleColor purple {
get { return new BubbleColor(Name.purple, new Color (0.5f, 0f, 1f, 1f)); }
}
public static BubbleColor brown {
get { return new BubbleColor(Name.brown, new Color (0.6f, 0.25f, 0.1f, 1f)); }
}
}
The reason I added an enum to the class is because I need to compare colors often, but what worries me is that will result in creating a bunch of new colors every time I test:
if (myColor.name == BubbleColor.purple.name) {}
Does calling BubbleColor.purple actually create a new instance of BubbleColor each time or is it somehow stored in the class considering that it's static. I ended up doing something like for fear of creating new instances all the time:
public static readonly BubbleColor purple = new BubbleColor(Name.purple, new Color (0.5f, 0f, 1f));
public static readonly BubbleColor brown = new BubbleColor(Name.brown, new Color (0.6f, 0.3f, 0.1f));
Very well-arranged program$$anonymous$$g style btw. $$anonymous$$eep it up!
Answer by shaderop · Jul 10, 2013 at 08:45 PM
Your worries aren't misplaced. The static property will create a new instance every time it's called, because it's just syntax sugar for a method call. The compiler might be able to optimize some of those allocations, but it's best not to rely on that.
Your second solution with the public static readonly
fields is a much better solution IMHO, and I personally find it more readable.
Answer by Nanity · Jul 10, 2013 at 08:42 PM
Easiest way would be to check:
if (BubbleColor.purple == BubbleColor.purple)
Debug.Log("It's stored in the static struct");
else
Debug.Log("Created new on each call");
This might work for reference types that don't override the Equals method, but I'm pretty sure it won't work for structs
.
You're right, and would have been quicker than writing this question but I wanted to know if there was some hidden "magic" somewhere.
Anyway, I did try it and effectively it does create a new instance on each call ;)
Your answer
Follow this Question
Related Questions
Surface Shader issue: property color gets changed 0 Answers
property.FindPropertyRelative("property") works only for attributes but not actual properties? 1 Answer
Material doesn't have a color property '_Color' 4 Answers
Get mesh name with mouse click, then change color (and other properties) of mesh 2 Answers