Reputation: 14112
I am reading a CSV file and I would like to cache the results in an array.
This is my getter/setter:
private RedirectionRule[] RedirectionRules
{
get
{
if (_redirectionRules == null)
{
return new RedirectionRule[MAXLENGTH];
}
return _redirectionRules;
}
set
{
_redirectionRules = value;
}
}
Is this the right approach to an optimal way of caching the results?
Upvotes: 0
Views: 818
Reputation: 128407
I don't think there's much point in returning a new array in your getter when _redirectionRules
is null
. If you set the property in your code that parses the CSV, then it will be cached.
In other words, somewhere you should have a function like this to parse the CSV data (as an example, I've put it in the RedirectionRule
class, but you could have a RedirectionRuleParser
class or something like that depending on your needs):
class RedirectionRule {
public static RedirectionRule Parse(string text) {
// some code here to parse text for your RedirectionRule object
}
public static RedirectionRule[] ParseCsv(string csv) {
string[] values = csv.Split(',');
RedirectionRule[] rules = new RedirectionRule[values.Length];
for (int i = 0; i < values.Length; i++) {
rules[i] = RedirectionRule.Parse(values[i]);
}
}
}
Then, if you have code like this somewhere, you are caching the data:
string csv = "RuleType1,RuleType1,RuleType1";
RedirectionRules = RedirectionRule.ParseCsv(csv);
Elsewhere, where you want to access the data you have cached:
if (RedirectionRules != null) {
// do something with your cached data
} else {
// I don't know, throw an exception or something
}
The only thing your example code would accomplish by creating a new RedirectionRule[MAXLENGTH]
array in your property's getter would be to sneak past the RedirectionRules != null
check above, thereby opening up the possibility of accessing data that looks like it's been cached but really came out of thin air.
Upvotes: 1
Reputation: 795
I'm not sure I understand the question really, as I am not sure which of the following questions you are asking
Perhaps you were asking all 3, so I will do my best to answer all 3
Upvotes: 1
Reputation: 64648
Hard to say in general, it depends on what you need exactly.
Just another thought: When you create a full sized array in the getter, why do you need a setter anymore? There should probably be only one place where the array is created, just to keep it clean.
Then - when you create the array once, and this for sure, why not creating it in the constructor?
Upvotes: 0