Performance penalty of typecasting and boxing/unboxing types in C# when storing generic values
- by kitsune
I have a set-up similar to WPF's DependencyProperty and DependencyObject system. My properties however are generic. A BucketProperty has a static GlobalIndex (defined in BucketPropertyBase) which tracks all BucketProperties. A Bucket can have many BucketProperties of any type. A Bucket saves and gets the actual values of these BucketProperties... now my question is, how to deal with the storage of these values, and what is the penalty of using a typecasting when retrieving them? I currently use an array of BucketEntries that save the property values as simple objects. Is there any better way of saving and returning these values?
Beneath is a simpliefied version:
public class BucketProperty<T> : BucketPropertyBase
{
}
public class Bucket
{
private BucketEntry[] _bucketEntries;
public void SaveValue<T>(BucketProperty<T> property, T value)
{
SaveBucketEntry(property.GlobalIndex, value)
}
public T GetValue<T>(BucketProperty<T> property)
{
return (T)FindBucketEntry(property.GlobalIndex).Value;
}
}
public class BucketEntry
{
private object _value;
private uint _index;
public BucketEntry(uint globalIndex, object value)
{
...
}
}