I've run into some speed issues with regards to structs and delegates - take the following console application code:
public delegate string StringGetter();
public class LocalString
{
public LocalString(string value)
{
this.value = value;
}
public StringGetter Getter
{
get
{
return new StringGetter(this.GetValue);
}
}
private string GetValue()
{
return value;
}
private string value;
}
class Program
{
static void Main(string[] args)
{
var start = DateTime.Now;
for (int i = 0; i < 2000000; i++)
{
var val = new LocalString( "hello World" );
val.Getter();
}
Console.WriteLine((DateTime.Now - start).TotalMilliseconds);
Console.ReadKey();
}
}
When executed on my machine it takes ~1.8 secs...If I change the struct to a class it runs in ~0.1secs. I've had a look at the underlying assembly code and open source ROTOR code to see why and there is some special code for delegates that have a struct target which I'm guessing is for handling boxing and unboxing in function MethodDesc* COMDelegate::GetDelegateCtor(TypeHandle delegateType, MethodDesc *pTargetMethod, DelegateCtorArgs *pCtorData).
Another point - if you build this in VS2008 targeting .net 3.5 the app runs faster than if you run it in VS2010 targeting .net 3.5. I haven't figured out why this is.
Any comments / better enlightenment would be welcome...
Regards Lee