views:

188

answers:

1

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)
        {
            ...
        }
}
A: 

I've created a very similar setup after reading through Rockford Lhotka's book on Business Objects but I avoided the object boxing issue by forcing the implementer of the property to maintain a typed backing field instead. I know this is a trade off but in my case I valued performance over the simplicity of declaring new properties. In order to manage the type throughout the property lookups and management I use Lambda expressions and generics very heavily and so far so good, I'm beating the performance of Dependency Objects and CSLA.

To answer your question, yes you will have a performance hit by using object boxing and also for value types backed by these properties you will be storing keeping an extra pointer in the heap for each value which in general would double the memory footprint for these values. As far as how much a performance hit you will take it depends on how regularly read and write to these properties amongst other factors. If you want to get a feel for the performance difference it would probably be a good idea to make a small test app that runs a loop and boxes some integers as an object and un-boxes them versus storing the same values in a regular field. My guess is that by not doing object boxing and un-boxing you will likely increase your performance at least 2-fold but don't take my word do the test.

jpierson