我目前正在做一些最后的优化,主要是为了好玩和学习,并发现了一些让我有几个问题的东西。
首先,问题:
- 当我通过使用DynamicMethod构造内存中的方法并使用调试器时,在反汇编视图中查看代码时,有什么方法可以让我进入生成的汇编代码?调试器似乎只是为我跳过了整个方法
- 或者,如果这不可能,我是否可以以某种方式将生成的 IL 代码作为程序集保存到磁盘,以便我可以使用Reflector检查它?
- 为什么
Expression<...>
我的简单加法版本 (Int32+Int32 => Int32) 比最小的 DynamicMethod 版本运行得更快?
这是一个简短而完整的演示程序。在我的系统上,输出是:
DynamicMethod: 887 ms
Lambda: 1878 ms
Method: 1969 ms
Expression: 681 ms
我希望 lambda 和方法调用具有更高的值,但 DynamicMethod 版本始终慢约 30-50%(可能由于 Windows 和其他程序而有所不同)。有人知道原因吗?
这是程序:
using System;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Diagnostics;
namespace Sandbox
{
public class Program
{
public static void Main(String[] args)
{
DynamicMethod method = new DynamicMethod("TestMethod",
typeof(Int32), new Type[] { typeof(Int32), typeof(Int32) });
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ret);
Func<Int32, Int32, Int32> f1 =
(Func<Int32, Int32, Int32>)method.CreateDelegate(
typeof(Func<Int32, Int32, Int32>));
Func<Int32, Int32, Int32> f2 = (Int32 a, Int32 b) => a + b;
Func<Int32, Int32, Int32> f3 = Sum;
Expression<Func<Int32, Int32, Int32>> f4x = (a, b) => a + b;
Func<Int32, Int32, Int32> f4 = f4x.Compile();
for (Int32 pass = 1; pass <= 2; pass++)
{
// Pass 1 just runs all the code without writing out anything
// to avoid JIT overhead influencing the results
Time(f1, "DynamicMethod", pass);
Time(f2, "Lambda", pass);
Time(f3, "Method", pass);
Time(f4, "Expression", pass);
}
}
private static void Time(Func<Int32, Int32, Int32> fn,
String name, Int32 pass)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (Int32 index = 0; index <= 100000000; index++)
{
Int32 result = fn(index, 1);
}
sw.Stop();
if (pass == 2)
Debug.WriteLine(name + ": " + sw.ElapsedMilliseconds + " ms");
}
private static Int32 Sum(Int32 a, Int32 b)
{
return a + b;
}
}
}