7

我有一个简单的场景,我试图在股票对象列表上测试表达式编译树的性能。下面是代码

表达式编译树的性能比静态 lambda 调用慢 5 倍。我不确定这是否是表达式编译树的标准性能。将不胜感激任何见解。

LambdaExpression();
List<Stock> stocks = new List<Stock>();
for (int ctr = 0; ctr <= 5000000; ctr++)
{
    Stock stk1 = new Stock() { Price = ctr, Symbol = "A", CloseDate = DateTime.Now, FaceValue = ctr } ;
    stocks.Add(stk1);
}
CompileTimeLamda(a);
DynamicLambda(a);


public static void LambdaExpression()
{
    ParameterExpression CS1 = Expression.Parameter(typeof(Stock), "d");

    var line1 = Expression.Equal(Expression.Property(CS1, typeof(Stock).GetProperty("Symbol")), Expression.Constant("MSFT", typeof(string)));
    var line2 = Expression.GreaterThan(Expression.Property(Expression.Property(CS1, typeof(Stock).GetProperty("CloseDate")),typeof(DateTime).GetProperty("Millisecond")), 
                                 Expression.Constant(0, typeof(int)));
    var line3 = Expression.GreaterThan(Expression.Property(CS1, typeof(Stock).GetProperty("Price")), Expression.Constant((double)0, typeof(double)));
    var line4 = Expression.And(line1,line2);
    var line5 = Expression.OrElse(line4, line3);

    func = Expression.Lambda<Func<Stock, bool>>(line5, new ParameterExpression[] {  CS1 } ).Compile();
}


public static void DynamicLambda(List<Stock> stks)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    foreach (var d in stks)
    {
        func(d);
    }
    watch.Stop();
    Console.WriteLine("Dynamic Lambda :" + watch.ElapsedMilliseconds);
}

public static void CompileTimeLamda(List<Stock> stks)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    foreach (var d in stks)
    {
        if (d.Symbol == "MSFT" && d.CloseDate.Millisecond > 0 ||
                                  (d.Price) > 0) ;
    }
    watch.Stop();
    Console.WriteLine("Compile Time Lamda " +watch.ElapsedMilliseconds);
}
4

3 回答 3

7

我对自己进行了一些测试,比较了 lambda 表达式、编译表达式树、直接函数调用和内联代码。结果非常有趣。我几乎认为我的测试有问题,因为表达式树更快,但我想这并非不可能。lambda 表达式是最慢的!!有趣的是,表达式树比函数调用快,只比内联代码慢一点。完全不是我所期望的。

编辑:实际上我会认为 lambda 和编译函数在下面的结果中速度相等

    void TestIt()
    {
        var ints = new int[10000000];
        Random rand = new Random();
        for (int i = 0; i < ints.Length; i++)
            ints[i] = rand.Next(100);

        Func<int, int> func1 = i => i + 2;
        Func<int, int> func2 = CompileIt();

        var stopwatch = new Stopwatch();

        for (int x = 0; x < 3; x++)
        {
            stopwatch.Restart();
            for (int i = 0; i < ints.Length; i++)
                ints[i] = func1(ints[i]);
            stopwatch.Stop();
            Console.Write("Lamba                       ");
            Console.Write(stopwatch.ElapsedMilliseconds);
            ShowSum(ints);

            stopwatch.Restart();
            for (int i = 0; i < ints.Length; i++)
                ints[i] = func2(ints[i]);
            stopwatch.Stop();
            Console.Write("Lambda from expression tree ");
            Console.Write(stopwatch.ElapsedMilliseconds);
            ShowSum(ints);

            stopwatch.Restart();
            for (int i = 0; i < ints.Length; i++)
                ints[i] = AddTwo(ints[i]);
            stopwatch.Stop();
            Console.Write("Compiled function           ");
            Console.Write(stopwatch.ElapsedMilliseconds);
            ShowSum(ints);

            stopwatch.Restart();
            for (int i = 0; i < ints.Length; i++)
                ints[i] = ints[i] + 2;
            stopwatch.Stop();
            Console.Write("Compiled code               ");
            Console.Write(stopwatch.ElapsedMilliseconds);
            ShowSum(ints);
        }
    }

    private int AddTwo(int value)
    {
        return value + 2;
    }

    private void ShowSum(int[] ints)
    {
        Console.WriteLine("    Sum = " + ints.Sum(i => i).ToString());
    }

    private Func<int, int> CompileIt()
    {
        var param1 = Expression.Parameter(typeof(int));
        Expression body = Expression.Add(param1, Expression.Constant(2));
        return Expression.Lambda<Func<int, int>>(body, new [] { param1 }).Compile();
    }

3次运行的结果是:

Lamba                       164    Sum = 515074919
Lambda from expression tree 86    Sum = 535074919
Compiled function           155    Sum = 555074919
Compiled code               54    Sum = 575074919

Lamba                       153    Sum = 595074919
Lambda from expression tree 88    Sum = 615074919
Compiled function           156    Sum = 635074919
Compiled code               53    Sum = 655074919

Lamba                       156    Sum = 675074919
Lambda from expression tree 88    Sum = 695074919
Compiled function           157    Sum = 715074919
Compiled code               54    Sum = 735074919
于 2012-07-26T22:23:13.313 回答
3

如果您在编译时而不是在运行时编译,差异与编译器拥有更多信息并花费更多精力优化代码有关......此外,使用 lambda,您将拥有一个更“灵活”的程序(您可以在运行时选择 lambda)。这是以额外的函数调用为代价的,并且失去了许多潜在的优化。

为了进行更“公平”的比较,您可以使用以下方式比较静态 lambda 与动态 lambda:

Func<Stock, bool> compileTime = (Stock d) => (d.Symbol == "MSFT" && d.CloseDate.Millisecond > 0) || d.Price > 0;

而不是硬编码的代码..

在那里你也会发现差异,但稍微小一点......差异是出于相同的原因(更多优化)......您可以通过手动优化您的 lambda 来减少差异(尽管这并不总是可能的,因为编译器可以创建无法使用 lambda 手动创建的有效 CLI 代码)。

但是例如,如果您将动态 lambda 从以下位置更改:

var line5 = Expression.OrElse(line4, line3);

到:

var line5 = Expression.OrElse(line3, line4);

您将看到 lambda 如何在原始编译代码的 1 倍和 2 倍之间执行。

于 2012-07-26T21:37:54.080 回答
0

这里是利用手动访问表达式并发出有效代码的替代方法。

于 2015-11-24T11:45:21.760 回答