Hello there,

As known cli allows trick with casting of arrays of inherited types. If A is
B then A[] is B[]. This is the only case when VM allows cast from one type
to another different type that is not in inheritance hierarchy. Due to this
trick, runtime have always to check types in array setters. This check
however is related to ref types only, indeed, there is no real inheritance
on value types.

Basing on such principal difference of arrays of ref types and value types
I've created simple test of array of objects and array of value type that
wrap the same object.

struct Wrapper
{
    public object value; // any ref type can be used here
}

static void ArrayTest(int cycles)
{
    // Array of objects
    object[] objectArray = new object[1];  // any ref type can be used here
    string value = "test";
    DateTime start = DateTime.Now;

    for(int i = 0; i < cycles; i++)
    {
        objectArray[0] = value;
    }

    DateTime end = DateTime.Now;

    Console.WriteLine("Time of array of objects: " + (end - start));

    // Array of wrappers
    Wrapper[] wrapperArray = new Wrapper[1];

    start = DateTime.Now;

    for(int i = 0; i < cycles; i++)
    {
        wrapperArray[0].value = value;
    }

    end = DateTime.Now;
    Console.WriteLine("Time of array of wrappers: " + (end - start));
}

Though il code for value type array does not looks very pretty, and though
JIT does not optimezes as it should be such value type operations, results
of value type array are about 25% faster then object array. Moreover, the
more derived class I use as array's element the more slower array of objects
works.

All test I've performed on .NET Framework 1.1.

Conclusion:
It's preferable to use array of such wrappers instead array of objects, if
there is no need to cast such array to array of element's base type. I see a
lot of such places in bcl (collections, for instance).

P.S. Actually I consider that array cast trick as an example of bad design.
The value of such cast is doubtful, but speed penalties are considerable.
For instance C++ has no such kind of cast.
--
Vladimir Nesterovsky
visit: http://constcli.sscli.net
e-mail: [EMAIL PROTECTED], [EMAIL PROTECTED]
home: http://www.nesterovsky-bros.com

Reply via email to