{"id":61,"date":"2010-05-19T19:18:00","date_gmt":"2010-05-19T17:18:00","guid":{"rendered":"http:\/\/dev.bratched.fr\/en\/?p=61"},"modified":"2010-05-19T19:18:00","modified_gmt":"2010-05-19T17:18:00","slug":"dynamic-methods-in-net","status":"publish","type":"post","link":"https:\/\/bratched.com\/en\/2010\/05\/19\/dynamic-methods-in-net\/","title":{"rendered":"Dynamic methods in .NET"},"content":{"rendered":"<p>Using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/f7ykdhsy(VS.71).aspx\" rel=\"nofollow\">reflection<\/a> to invoke methods which are not known at compile time might be problematic in performance critical applications. It is roughly 2.5-3.0 times slower than direct method calls. Here\u2019s a sample test I\u2019ve conducted:<\/p>\n<div id=\"scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:0c8078d0-64de-4fc4-b313-374421865196\" class=\"wlWriterSmartContent\" style=\"margin: 0px;padding: 0px;float: none\">\n<pre class=\"lang:default decode:true\">class Program\n    {\n        [DllImport(\"kernel32.dll\")]\n        static extern void QueryPerformanceCounter(ref long ticks);\n\n        static PropertyInfo _intProp = typeof(Foo).GetProperty(\"IntProp\", BindingFlags.Public | BindingFlags.Instance);\n\n        static void Main(string[] args)\n        {\n            Foo foo = new Foo { IntProp = 10 };\n            const int COUNT = 1;\n            Console.WriteLine(Measure(() =&gt; ReadPropertyWithReflection(foo), COUNT));\n            Console.WriteLine(Measure(() =&gt; ReadPropertyDirectly(foo), COUNT));\n        }\n\n        static void ReadPropertyWithReflection(Foo foo)\n        {\n            int intProp = (int)_intProp.GetValue(foo, null);\n        }\n\n        static void ReadPropertyDirectly(Foo foo)\n        {\n            int intProp = foo.IntProp;\n        }\n\n        static long Measure(Action action, int count)\n        {\n            long startTicks = 0;\n            QueryPerformanceCounter(ref startTicks);\n            for (int i = 0; i &lt; count; i++)\n            {\n                action();\n            }\n            long endTicks = 0;\n            QueryPerformanceCounter(ref endTicks);\n            return endTicks - startTicks;\n        }\n\n        class Foo\n        {\n            public int IntProp { get; set; }\n        }\n    }<\/pre>\n<\/div>\n<p>Here are the results:<\/p>\n<table border=\"1\" width=\"400\" cellspacing=\"0\" cellpadding=\"2\">\n<tbody>\n<tr>\n<td valign=\"top\" width=\"200\"><strong>Method<\/strong><\/td>\n<td valign=\"top\" width=\"198\"><strong>CPU units<\/strong><\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"200\">Direct method invocation<\/td>\n<td valign=\"top\" width=\"198\">796<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"200\">Reflection method invocation<\/td>\n<td valign=\"top\" width=\"198\">1986<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>So using reflection to perform a single property read is 2.5 slower than direct property access.<\/p>\n<p>Dynamic methods can be used to generate and execute a method at run time, without having to declare a dynamic assembly and a dynamic type to contain the method. They are the most efficient way to generate and execute small amounts of code.<!--more--> Here\u2019s an example of using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.reflection.emit.dynamicmethod.aspx\" rel=\"nofollow\">DynamicMethod<\/a> class to generate a getter for a given property:<\/p>\n<div id=\"scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8054fa8e-357e-4415-ac4a-e989a28e5720\" class=\"wlWriterSmartContent\" style=\"margin: 0px;padding: 0px;float: none\">\n<pre class=\"lang:default decode:true\">static Func&lt;Arg0, TReturn&gt; EmitGetter&lt;Arg0, TReturn&gt;(PropertyInfo propertyInfo)\n    {\n        MethodInfo mi = propertyInfo.GetGetMethod();\n        DynamicMethod dm = new DynamicMethod(\n            \"_get\",\n            typeof(TReturn),\n            new Type[] { typeof(Arg0) },\n            propertyInfo.DeclaringType);\n\n        ILGenerator il = dm.GetILGenerator();\n        il.Emit(OpCodes.Ldarg_0);\n        il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);\n        il.EmitCall(OpCodes.Callvirt, mi, null);\n        il.Emit(OpCodes.Ret);\n\n        return (Func&lt;Arg0, TReturn&gt;)dm.CreateDelegate(typeof(Func&lt;Arg0, TReturn&gt;));\n    }<\/pre>\n<\/div>\n<p>Now using this method we can emit a getter method from a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.reflection.propertyinfo.aspx\" rel=\"nofollow\">PropertyInfo<\/a> at run time and execute the returned delegate:<\/p>\n<div id=\"scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:a9783508-2fd4-4d82-93a9-eee85e4076ac\" class=\"wlWriterSmartContent\" style=\"margin: 0px;padding: 0px;float: none\">\n<pre class=\"lang:default decode:true\">Func&lt;Foo, int&gt; getter = EmitGetter&lt;Foo, int&gt;(_intProp);\n    Console.WriteLine(Measure(() =&gt; getter(foo), COUNT));<\/pre>\n<\/div>\n<p>And here are the final results I\u2019ve obtained using three different methods to read a property value:<\/p>\n<table border=\"1\" width=\"400\" cellspacing=\"0\" cellpadding=\"2\">\n<tbody>\n<tr>\n<td valign=\"top\" width=\"200\"><strong>Method<\/strong><\/td>\n<td valign=\"top\" width=\"198\"><strong>CPU units<\/strong><\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"200\">Direct method invocation<\/td>\n<td valign=\"top\" width=\"198\">796<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"200\">Dynamic method invocation<\/td>\n<td valign=\"top\" width=\"198\">1190<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"200\">Reflection method invocation<\/td>\n<td valign=\"top\" width=\"198\">1986<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n","protected":false},"excerpt":{"rendered":"<p>Using reflection to invoke methods which are not known at compile time might be problematic in performance critical applications. It is roughly 2.5-3.0 times slower than direct method calls. Here\u2019s a sample test I\u2019ve conducted: class Program { [DllImport(&#8220;kernel32.dll&#8221;)] static extern void QueryPerformanceCounter(ref long ticks); static PropertyInfo _intProp = typeof(Foo).GetProperty(&#8220;IntProp&#8221;, BindingFlags.Public | BindingFlags.Instance); static void [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[263,266],"tags":[284,312],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts\/61"}],"collection":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/comments?post=61"}],"version-history":[{"count":0,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts\/61\/revisions"}],"wp:attachment":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/media?parent=61"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/categories?post=61"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/tags?post=61"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}