Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么表达式delegat匹配比il代码快_C#_.net_Expression_Cil - Fatal编程技术网

C# 为什么表达式delegat匹配比il代码快

C# 为什么表达式delegat匹配比il代码快,c#,.net,expression,cil,C#,.net,Expression,Cil,我有下一个测试代码: 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

我有下一个测试代码:

    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);
    }
publicstaticvoidtest1()
{
var a=表达式参数(typeof(int),“a”);
VarB=表达式参数(typeof(int),“b”);
var expression=expression.Lambda(expression.Block(expression.Add(a,b)),a,b);
var f=expression.Compile();
f(1,2);
var sw=Stopwatch.StartNew();
对于(变量i=0;i
和定时:617毫秒对880毫秒。 你有什么想法吗? 我检查网络源代码:


非常感谢。

您是否比较了两种情况下JIT生成的真实机器代码?是的。是的。代码相同。逐行。在这种情况下,如何提高il代码的性能?(除使用x86外)我正在尝试此“dm.CreateDelegate(typeof(Func),new object())”并遇到以下异常:无法绑定到目标方法,因为其签名或安全透明性与委托类型的签名或安全透明性不兼容。