使用.NET 3.5调用多个表达式

时间:2015-03-02 18:36:56

标签: c# performance lambda expression-trees

替代解决方案

虽然我(并且对于这个项目仍然是)仅限于.NET 3.5,但我已经成功使用了表达树的DLR版本。这是在Apache License 2.0版下发布的。

这增加了对所有(可能是一些或多或少,但可能不是).NET 4.0+表达式的支持,例如BlockExpression,我需要这个问题。

The source code can be found on GitHub.


原始问题

在我目前的项目中,我正在使用可变数量的参数编译表达式树。我有一个Expressions链需要调用。在.NET 4.0+中,我只是使用Expression.Block来实现这一点,但是,我只能在这个项目中使用.NET 3.5。

现在我已经找到了解决这个问题的大规模黑客攻击,但我不相信这是解决这个问题的最好办法。

代码:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

class Program
{
    struct Complex
    {
        public float Real;
        public float Imaginary;
    }

    // Passed to all processing functions
    class ProcessContext
    {
        public ConsoleColor CurrentColor;
    }

    // Process functions. Write to console as example.
    static void processString(ProcessContext ctx, string s)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("String: " + s); }
    static void processAltString(ProcessContext ctx, string s)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("AltString: " + s); }
    static void processInt(ProcessContext ctx, int i)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("Int32: " + i); }
    static void processComplex(ProcessContext ctx, Complex c)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("Complex: " + c.Real + " + " + c.Imaginary + "i"); }

    // Using delegates to access MethodInfo, just to simplify example.
    static readonly MethodInfo _processString = new Action<ProcessContext, string>(processString).Method;
    static readonly MethodInfo _processAltString = new Action<ProcessContext, string>(processAltString).Method;
    static readonly MethodInfo _processInt = new Action<ProcessContext, int>(processInt).Method;
    static readonly MethodInfo _processComplex = new Action<ProcessContext, Complex>(processComplex).Method;

    static void Main(string[] args)
    {
        var methodNet40 = genNet40();
        var methodNet35 = genNet35();

        var ctx = new ProcessContext();
        ctx.CurrentColor = ConsoleColor.Red;

        methodNet40(ctx, "string1", "string2", 101, new Complex { Real = 5f, Imaginary = 10f });
        methodNet35(ctx, "string1", "string2", 101, new Complex { Real = 5f, Imaginary = 10f });


        // Both work and print in red:

        // String: string1
        // AltString: string2
        // Int32: 101
        // Complex: 5 + 10i
    }

    static void commonSetup(out ParameterExpression pCtx, out ParameterExpression[] parameters, out Expression[] processMethods)
    {
        pCtx = Expression.Parameter(typeof(ProcessContext), "pCtx");

        // Hard-coded for simplicity. In the actual code these are reflected.
        parameters = new ParameterExpression[]
        {
            // Two strings, just to indicate that the process method
            // can be different between the same types.
            Expression.Parameter(typeof(string), "pString"),
            Expression.Parameter(typeof(string), "pAltString"),
            Expression.Parameter(typeof(int), "pInt32"),
            Expression.Parameter(typeof(Complex), "pComplex")
        };

        // Again hard-coded. In the actual code these are also reflected.
        processMethods = new Expression[]
        {
            Expression.Call(_processString, pCtx, parameters[0]),
            Expression.Call(_processAltString, pCtx, parameters[1]),
            Expression.Call(_processInt, pCtx, parameters[2]),
            Expression.Call(_processComplex, pCtx, parameters[3]),
        };
    }

    static Action<ProcessContext, string, string, int, Complex> genNet40()
    {
        ParameterExpression pCtx;
        ParameterExpression[] parameters;
        Expression[] processMethods;
        commonSetup(out pCtx, out parameters, out processMethods);

        // What I'd do in .NET 4.0+
        var lambdaParams = new ParameterExpression[parameters.Length + 1]; // Add ctx
        lambdaParams[0] = pCtx;
        Array.Copy(parameters, 0, lambdaParams, 1, parameters.Length);

        var method = Expression.Lambda<Action<ProcessContext, string, string, int, Complex>>(
            Expression.Block(processMethods),
            lambdaParams).Compile();

        return method;
    }

    static Action<ProcessContext, string, string, int, Complex> genNet35()
    {
        ParameterExpression pCtx;
        ParameterExpression[] parameters;
        Expression[] processMethods;
        commonSetup(out pCtx, out parameters, out processMethods);

        // Due to the lack of the Block expression, the only way I found to execute
        // a method and pass the Expressions as its parameters. The problem however is
        // that the processing methods return void, it can therefore not be passed as
        // a parameter to an object.

        // The only functional way I found, by generating a method for each call,
        // then passing that as an argument to a generic Action<T> invoker with
        // parameter T that returns null. A super dirty probably inefficient hack.

        // Get reference to the invoke helper
        MethodInfo invokeHelper =
            typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
            .Single(x => x.Name == "invokeHelper" && x.IsGenericMethodDefinition);

        // Route each processMethod through invokeHelper<T>
        for (int i = 0; i < processMethods.Length; i++)
        {
            // Get some references
            ParameterExpression param = parameters[i];
            Expression process = processMethods[i];

            // Compile the old process to Action<T>
            Type delegateType = typeof(Action<,>).MakeGenericType(pCtx.Type, param.Type);
            Delegate compiledProcess = Expression.Lambda(delegateType, process, pCtx, param).Compile();

            // Create a new expression that routes the Action<T> through invokeHelper<T>
            processMethods[i] = Expression.Call(
                invokeHelper.MakeGenericMethod(param.Type),
                Expression.Constant(compiledProcess, delegateType),
                pCtx, param);
        }

        // Now processMethods execute and then return null, so we can use it as parameter
        // for any function. Get the MethodInfo through a delegate.
        MethodInfo call2Helper = new Func<object, object, object>(Program.call2Helper).Method;

        // Start with the last call
        Expression lambdaBody = Expression.Call(call2Helper,
            processMethods[processMethods.Length - 1],
            Expression.Constant(null, typeof(object)));

        // Then add all the previous calls
        for (int i = processMethods.Length - 2; i >= 0; i--)
        {
            lambdaBody = Expression.Call(call2Helper,
                processMethods[i],
                lambdaBody);
        }

        var lambdaParams = new ParameterExpression[parameters.Length + 1]; // Add ctx
        lambdaParams[0] = pCtx;
        Array.Copy(parameters, 0, lambdaParams, 1, parameters.Length);

        var method = Expression.Lambda<Action<ProcessContext, string, string, int, Complex>>(
            lambdaBody,
            lambdaParams).Compile();

        return method;
    }

    static object invokeHelper<T>(Action<ProcessContext, T> method, ProcessContext ctx, T parameter)
    {
        method(ctx, parameter);
        return null;
    }

    static object call2Helper(object p1, object p2) { return null; }
}

我想找到一个好的替代方案的主要原因是不必将这个丑陋的黑客放在我们的代码库中(尽管如果没有合适的替代方案我会这样做。)

虽然它也很浪费,但它运行在一台可能很弱的客户端机器上,在视频游戏中每秒可能有几千次。现在它不会破坏或者让我们的游戏表现出色,但它并不是可以忽视的。每种方法的函数调用量。

  • .NET 4.0:1执行时编译和N方法调用。
  • .NET 3.5:1 + N编译和3N + 1方法调用(尽管可以优化到大约2N + log N)。

测试性能(在发布版本中)在调用过程中产生3.6倍的差异。在调试中,它的速度差异约为6倍,但这并不重要,我们的开发人员拥有更强大的机器。

2 个答案:

答案 0 :(得分:5)

即使您保持相同(或类似的)基本策略但稍微重构代码,您也可以简化代码。

编写自己的Block实现,该实现接受一系列表达式并创建一个表示调用所有表达式的表达式。

要执行此操作,您将拥有一个私有实现方法,该方法需要执行大量操作并调用所有这些操作,您将把所有表达式转换为传递给方法的操作,然后就可以了返回表示该方法调用的表达式:

//TODO come up with a better name
public class Foo
{
    private static void InvokeAll(Action[] actions)
    {
        foreach (var action in actions)
            action();
    }
    public static Expression Block(IEnumerable<Expression> expressions)
    {
        var invokeMethod = typeof(Foo).GetMethod("InvokeAll",
            BindingFlags.Static | BindingFlags.NonPublic);
        var actions = expressions.Select(e => Expression.Lambda<Action>(e))
            .ToArray();
        var arrayOfActions = Expression.NewArrayInit(typeof(Action), actions);
        return Expression.Call(invokeMethod, arrayOfActions);
    }
}

这不涉及提前编译任何表达式,但更重要的是它允许您从您的使用中分离创建表达式块的逻辑,允许您根据什么版本轻松地将其输入/输出你正在使用的框架。

答案 1 :(得分:0)

我认为没有理由为你想要调用的每个动作编译一个lambda。使处理函数返回void以外的其他内容。然后你可以生成:

static object Dummy(object o1, object o2, object o3, ...) { return null; }

Dummy(func1(), func2(), func3());
然后应该

Dummy内联。

即使你必须编译多个lambda,你也不需要在运行时接受委托调用。您可以访问已编译的lambda的Delegate.Method并直接发出对该方法的静态调用。