>Hi,
>
>Also interesting is the opcode difference between the two versions.
>The faster, generic version actually has about 25% more code (mainly because of two occurences of 'constrained' - whatever that is)
>
hi Viv,
First, the 25% more ildasm code does not tell anything about execution speed - I believe
Hadn't looked at the ildasm of the generic method.
A hunch tells me it 'constrains' the type of the arg to «T»
I made this small example
class xxx«T» where T : IComparable«T»
{
T yyy;
public bool compare(T xxx)
{
return yyy.CompareTo(xxx) < 0;
}
}
and had a look at the ildasm
.method public hidebysig instance bool compare(!T xxx) cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldflda !0 class GregoryAdam.Test.xxx`1«!T»::yyy
IL_0006: ldarg.1
IL_0007: constrained. !T
IL_000d: callvirt instance int32 class [mscorlib]System.IComparable`1«!T»::CompareTo(!0)
IL_0012: ldc.i4.0
IL_0013: clt
IL_0015: ret
} // end of method xxx`1::compare
See, it loads arg1 and constrains it to type T
My feeling is that this is a message to the JIT compiler
___
read this:
http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained.aspxConstained
- for generic code
- works also for non-generic types
- there's more to it than just generics
The constrained prefix is designed to allow callvirt instructions to be made in a uniform way
independent of whether thisType is a value type or a reference type.
Haven't understood all of it - but I have learnt something new today ;)))
Gregory