mercredi 16 mai 2018

C# - Why is Delegate created with `Delegate.CreateDelegate` faster than lambda and method delegates?

All this time I've been reading about reflection, everybody is always saying: "reflection is slow", "reflection is slow".

Now I decided to test how slow, and for my surprise, a delegate created with reflection is actually about twice as fast as a delegate created with lambda, and, also surprisingly, about four times faster than delegates taking declared methods.

See the code

This is a custom class whose property get method will be used in the delegates:

#class to test
class SomeClass
{
    public SomeClass A { get; set; } //property to be gotten
    public static SomeClass GetA(SomeClass c) { return c.A; } //declared getter method
}

There are the three delegates I tested:

PropertyInfo AProp = typeof(SomeClass).GetProperty("A");

//1 - Created with reflection
Func<SomeClass, SomeClass> Getter = (Func<SomeClass, SomeClass>)Delegate.CreateDelegate(typeof(Func<SomeClass, SomeClass>), null, AProp.GetGetMethod());

//2 - Created with a lambda expression
Func<SomeClass, SomeClass> Getter2 = c => c.A;

//3 - Created from a declared method
Func<SomeClass, SomeClass> Getter3 = SomeClass.GetA;

These are the tests:

SomeClass C = new SomeClass();
C.A = new SomeClass(); //same times wheter A is set or null
Stopwatch w;

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter2(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter3(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

And the results:

enter image description here





Aucun commentaire:

Enregistrer un commentaire