Given the following code:
using System; using System.Reflection.Emit; using System.Diagnostics; using System.Reflection; namespace ConsoleApplication1 { class A { public int Do(int n) { return n; } } public delegate int DoDelegate(); class Program { public static void Main(string[] args) { A a = new A(); Stopwatch stopwatch = Stopwatch.StartNew(); int s = 0; for (int i = 0; i < 100000000; i++) { s += a.Do(i); } Console.WriteLine(stopwatch.ElapsedMilliseconds); Console.WriteLine(s); DynamicMethod dm = new DynamicMethod("Echo", typeof(int), new Type[] { typeof(int) }, true); ILGenerator il = dm.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ret); DynamicMethod dm2 = new DynamicMethod("Test", typeof(int), new Type[0]); il = dm2.GetILGenerator(); Label loopStart = il.DefineLabel(); Label loopCond = il.DefineLabel(); il.DeclareLocal(typeof(int));
Method call. Built in. The loop ends in about 40 ms. If, for example, I make Do a virtual function, it will not be inserted, and the cycle will end in 240 ms. So far, so good. When I use ILGenerator to generate the Do (Echo) method and then generate DynamicMethod with the same loop as this main method, calling the Echo method never becomes inlined, and it takes about 240 ms to complete the loop. The MSIL code is correct, as it returns the same result as the C # code. I was sure that the inlining method is something that JIT does, so I see no reason to not include the Echo method.
Does anyone know why this simple method will not be built into JIT.
source share