So let’s say I have a Clone object with these properties. Clone might have different mass or name based on the file it was loaded from, but these values never change at runtime. However, Clone instances to have some autonomy and properties which do change per instance, so they can’t all be the same instance.
public class Clone
{
public float Mass { get; protected set; }
public string Name { get; protected set; }
public Clone(string filePath)
{
Name = //read name from file
Mass = //read mass from file
}
}
Now, what I want to know is, what are the benefits and drawbacks (if any) of doing this instead:
public class CloneInfo
{
public float Mass;
}
public static class Database
{
public static Dictionary<string, CloneInfo> Lookup;
[...load whole dictionary from files...]
}
public class Clone
{
public string Name { get; protected set; }
public float Mass { get { return Database.Lookup[Name].Mass; } }
public Clone(string name)
{
Name = name;
}
}
With this ‘redirecting’ method, I keep the simple syntax of Clone.Mass, but don’t have to store a Mass value for each instance. Since I’ve got thousands of clones wandering about, this is a good thing. I’m mainly interested in ‘redirecting’ because of the syntax. I realize that I could simply manually do the database lookup every time I wanted a particular clone’s mass, but I’d rather keep the usage of the class nice and straightforward. Is there any drawback to this? Is the property going to be slower than direct lookup in the static database? Does the property take up any space in a Clone instance?
Or, perhaps, is this a use case C# already has an answer for which I’m not aware of? Seems like write-once properties which are common among many instances might be somewhere in this beautiful language.
If all the clones of a certain type have the same mass, that sounds like a job for subclassing:
More to the point of your question: if you are more constrained by memory than by processing time, your approach may give some benefit. If memory is plentiful, and cache performance is not an issue, the approach you suggest probably has little value. It certainly seems to complicate the code quite a bit.
The usual advice is: write simple code, measure the performance, and, if the performance is inadequate, address the performance bottlenecks. That way, you only have complicated code in places where it actually helps your application’s performance.
Another thought: instead of having have the clone index into the dictionary with the
Namestring, why not just have a CloneInfo field: