我有下一个测试代码:
public static void Test1()
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var expression = Expression.Lambda<Func<int,int,int>>(Expression.Block(Expression.Add(a,b)),a,b);
var f = expression.Compile();
f(1,2);
var sw = Stopwatch.StartNew();
for (var i = 0; i < int.MaxValue/10; i++)
{
f(1, 2);
}
sw.Stop();
Console.WriteLine("TestExpression - {0}", sw.Elapsed.TotalMilliseconds);
}
public static void Test2()
{
var dm = new DynamicMethod("Add", typeof(int), new[] {typeof(int), typeof(int)}, true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ret);
var f = (Func<int, int, int>) dm.CreateDelegate(typeof(Func<int, int, int>));
RuntimeHelpers.PrepareDelegate(f);
f(1, 2);
var sw = Stopwatch.StartNew();
for (var i = 0; i < int.MaxValue / 10; i++)
{
f(1, 2);
}
sw.Stop();
Console.WriteLine("TestIl - {0}", sw.Elapsed.TotalMilliseconds);
}
和时间:617毫秒vs 880毫秒。 你有什么想法? 我检查一下网络源代码: https://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Compiler/LambdaCompiler.cs,c5ff378c3a5f8142