c# - 使用 .NET 3.5 调用多个表达式

标签 c# performance lambda expression-trees

替代方案

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

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

The source code can be found on GitHub.


原始问题

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

现在我找到了解决此问题的大量 hack,但我认为这不是解决此问题的最佳方法。

代码:

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; }
}

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

另一方面,它也很浪费,而且它在一个可能很弱的客户端机器上运行,在视频游戏中每秒可能运行几千次。现在它不会破坏或影响我们游戏的性能,但它不可忽视。每种方法的函数调用量。

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

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

最佳答案

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

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

要做到这一点,您将拥有一个私有(private)实现方法,该方法采用许多操作并调用所有这些操作,您将把所有的表达式转换为传递给该方法的操作,然后您可以返回表示该方法调用的表达式:

//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);
    }
}

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

关于c# - 使用 .NET 3.5 调用多个表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28817010/

相关文章:

Java比较值,最好的方法

python - 如何提高Python在大数据集中的计算速度?

java - 我可以在运行时查询 lambda 函数的生命周期吗?

c# - 什么是隐藏依赖?

c# - 在 NInject 中实现 OnePerSessionBehavior

c# - C#代码隐藏中的多个不同的SQL更新命令

performance - 如何用动画过滤来展示大数据集?

google-sheets - 处理列表以特定格式输出

glass-fish 服务器的 java 8 lambda 表达式支持

c# - 为什么 JsonSerializer 给空?