All articles

Dynamic sebesség újra

Published 2010-05-17 - Last modified 2010-05-17

Original: https://soci.hu/blog/index.php/2010/05/17/dynamic-sebesseg-ujra/

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); } } } [/source] [source='C'] Reflection hívási idő: 00:00:02.5393161 Dynamic hívási idő: 00:00:00.2049100 A dynamic 12.3923444658829x gyorsabb volt. [/source] Ha ügyesebbek vagyunk, és kivesszük a ciklusból a reflection előkészítését: [source='C#'] 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); } } } [/source] [source='C'] Reflection hívási idő: 00:00:01.2058747 Dynamic hívási idő: 00:00:00.2044023 A dynamic 5.89951388765798x gyorsabb volt. [/source] Jó ez, szeretjük, pedig nem is COMolunk.