Dynamic sebesség újra
Hogy ne a levegőbe beszéljek:
using System;
using System.Diagnostics;
using System.Reflection;
namespace DynamicTypeTest
{
class Program
{
static void Main(string[] args)
{
object target = "alma";
object arg = "m";
string a2 = (string)arg;
Stopwatch w = Stopwatch.StartNew();
const int callNumber = 1000 * 1000;
for (int i = 0; i < callNumber; i++)
{
Type[] argTypes = new Type[] { typeof(string) };
MethodInfo mi = target.GetType().GetMethod("Contains", argTypes);
object[] oa = new object[] { a2 };
bool b = (bool)mi.Invoke(target, oa);
}
w.Stop();
Console.WriteLine("Reflection hívási idő: {0}", w.Elapsed);
double elapsedTickForReflection = w.ElapsedTicks;
w.Restart();
for (int i = 0; i < callNumber; i++)
{
bool b = ((dynamic)target).Contains(a2);
}
w.Stop();
Console.WriteLine("Dynamic hívási idő: {0}", w.Elapsed);
Console.WriteLine("A dynamic {0}x gyorsabb volt.", elapsedTickForReflection / w.ElapsedTicks);
}
}
}
Reflection hívási idő: 00:00:02.5393161 Dynamic hívási idő: 00:00:00.2049100 A dynamic 12.3923444658829x gyorsabb volt.
Ha ügyesebbek vagyunk, és kivesszük a ciklusból a reflection előkészítését:
using System;
using System.Diagnostics;
using System.Reflection;
namespace DynamicTypeTest
{
class Program
{
static void Main(string[] args)
{
object target = "alma";
object arg = "m";
string a2 = (string)arg;
Stopwatch w = Stopwatch.StartNew();
Type[] argTypes = new Type[] { typeof(string) };
MethodInfo mi = target.GetType().GetMethod("Contains", argTypes);
object[] oa = new object[] { a2 };
const int callNumber = 1000 * 1000;
for (int i = 0; i < callNumber; i++)
{
bool b = (bool)mi.Invoke(target, oa);
}
w.Stop();
Console.WriteLine("Reflection hívási idő: {0}", w.Elapsed);
double elapsedTickForReflection = w.ElapsedTicks;
w.Restart();
for (int i = 0; i < callNumber; i++)
{
bool b = ((dynamic)target).Contains(a2);
}
w.Stop();
Console.WriteLine("Dynamic hívási idő: {0}", w.Elapsed);
Console.WriteLine("A dynamic {0}x gyorsabb volt.", elapsedTickForReflection / w.ElapsedTicks);
}
}
}
Reflection hívási idő: 00:00:01.2058747 Dynamic hívási idő: 00:00:00.2044023 A dynamic 5.89951388765798x gyorsabb volt.
Jó ez, szeretjük, pedig nem is COMolunk.
May 19th, 2011 at 1:16 pm
Hali,
Ez érdekes, nekem pont ellentétes eredmény jött ki.
Van ötleted?
Üdv,
Zoli
May 19th, 2011 at 10:38 pm
Ugyanezzel a kóddal?