Vectors vs. Arrays

It’s interesting to note that the CLR supports two special types to deal with arrays in C# code. If your array happens to be single-dimensional, and it happens to have a lower bound of 0, which is usually true for C# arrays,6 then the CLR uses a special built-in type called a vector, which is actually a subtype of System.Array. The CLR supports special IL instructions defined to work directly with vectors. If your array is multidimensional, then a CLR vector type is not used and an array object is used instead. To demonstrate this, let’s take a quick look at some IL code generated by the following short example:

public class EntryPoint
{
static void Main() {
int val = 123;
int newVal;
int[] vector = new int[1];
int[,] array = new int[1,1];
vector[0] = val;
array[0,0] = val;
newVal = vector[0];
newVal = array[0,0];
}
}

Take a look at the generated IL for the Main method:

.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 46 (0x2e)
.maxstack 4
.locals init ([0] int32 val,
[1] int32 newVal,
[2] int32[] 'vector',
[3] int32[0...,0...] 'array')
IL_0000: nop
IL_0001: ldc.i4.s 123
IL_0003: stloc.0
IL_0004: ldc.i4.1
IL_0005: newarr [mscorlib]System.Int32
IL_000a: stloc.2
IL_000b: ldc.i4.1
IL_000c: ldc.i4.1
IL_000d: newobj instance void int32[0...,0...]::.ctor(int32,
int32)
IL_0012: stloc.3
IL_0013: ldloc.2
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0017: ldloc.3
IL_0018: ldc.i4.0
IL_0019: ldc.i4.0
IL_001a: ldloc.0
IL_001b: call instance void int32[0...,0...]::Set(int32,
int32,
int32)
IL_0020: ldloc.2
IL_0021: ldc.i4.0
IL_0022: ldelem.i4
IL_0023: stloc.1
IL_0024: ldloc.3
IL_0025: ldc.i4.0
IL_0026: ldc.i4.0
IL_0027: call instance int32 int32[0...,0...]::Get(int32,
int32)
IL_002c: stloc.1
IL_002d: ret
} // end of method EntryPoint::Main


Notice the difference between usages of the two C# arrays. On line IL_0005, the newarr IL instruction creates the instance represented by the vector variable. The multidimensional array held in the variable array is created on line IL_000d. In the first case, a native IL instruction handles the operation, whereas a regular constructor call handles the operation in the second case. Similarly, when accessing the elements, the ILinstructions stelem and ldelem, on lines IL_0016 and IL_0022 respectively, are used for the vector, whereas regular method calls handle the access to the elements of the multidimensional array.

Because vector support is handled by specific IL instructions tailored specifically for vectors, it’s safe to assume that vector use tends to be more efficient than multidimensional array use, even though instances of both derive from System.Array.

Source Of Information : Apress Accelerated C Sharp 2010

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner