Friday, October 5, 2007

Nipples Pierced Las Vegas

Dynamic Method performance

In an interesting article in MSDN Magazine addressed to different performance problems, in particular in connection with Reflection. I am particularly interested in the acclaimed dynamic performance of the methods available for the. NET Framework version 2.0. A simple test application showed that the article is right.
In the test application is an object, a string assigned to a million times. This first wired directly, then with dynamic method and modified via Reflection. The result is clear. The direct-wired method is of course the fastest, the dynamic method takes twice as long for it (which I still find very good) and means of reflection, it takes 100 times longer. What a gain!
the way, the Assembly I have studied with Lutz's Reflector to ensure that the loop will be in practice for all three variants.

And here's the code: public class


Program {private delegate void
DemoDelegate (Foo arg);

static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();

Foo f = new Foo();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
f.Text = "Hello World!";
}
stopwatch.Stop();
Console.WriteLine("Direct: {0}", stopwatch.Elapsed);

stopwatch.Reset();

DemoDelegate del = createMethod();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
del(f);
}
stopwatch.Stop();

Console.WriteLine("Dynamic method: {0}", stopwatch.Elapsed);

stopwatch.Reset();

PropertyInfo property = f.GetType().GetProperty("Text");
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
property.SetValue(f, "Hello World!", null);
}
stopwatch.Stop();
Console.WriteLine("Reflection: {0}", stopwatch.Elapsed);


Console.ReadKey();
}

private static DemoDelegate createMethod()
{
Type[] parameterTypes = new Type[] { typeof(Foo) };
DynamicMethod method = new DynamicMethod("Demo", null, parameterTypes, typeof(Program));

ILGenerator iLGenerator = method.GetILGenerator();
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit (OpCodes.Ldstr, "Hello World!");
MethodInfo setMethod = typeof (Foo) GetProperty ("Text") GetSetMethod ();..
iLGenerator.EmitCall (OpCodes.Call, setMethod, null);
iLGenerator.Emit (OpCodes.Ret);

return (DemoDelegate) method.CreateDelegate (typeof (DemoDelegate));}



} public class Foo {

private string _text;

public string Text {

get {return _text;} {set
_text = value;}}

}

0 comments:

Post a Comment