Are lambda functions faster than delegates/anonymous functions?

前端 未结 2 1662
情歌与酒
情歌与酒 2021-02-14 01:12

I assumed lambda functions, delegates and anonymous functions with the same body would have the same \"speed\", however, running the follo

2条回答
  •  走了就别回头了
    2021-02-14 01:54

    A lambda expression is an anonymous function. "Anonymous function" refers to either a lambda expression or an anonymous method (which is what you've called a "delegate" in your code).

    All three operations are using delegates. The second and third are both using lambda expressions. All three will execute in the same way, with the same performance characteristics.

    Note that there can be a difference in performance between:

    Func func = x => ...;
    for (int i = 0; i < 10000; i++) {
        CallFunc(func);
    }
    

    and

    for (int i = 0; i < 10000; i++) {
        CallFunc(x => ...) // Same lambda as before
    }
    

    It depends on whether the compiler is able to cache the delegate created by the lambda expression. That will in turn depend on whether it captures variables etc.

    For example, consider this code:

    using System;
    using System.Diagnostics;
    
    class Test
    {
        const int Iterations = 1000000000;
    
        static void Main()
        {
            AllocateOnce();
            AllocateInLoop();
        }
    
        static void AllocateOnce()
        {
            int x = 10;
    
            Stopwatch sw = Stopwatch.StartNew();
            int sum = 0;
            Func allocateOnce = y => y + x;
            for (int i = 0; i < Iterations; i++)
            {
                sum += Apply(i, allocateOnce);
            }
            sw.Stop();
            Console.WriteLine("Allocated once: {0}ms", sw.ElapsedMilliseconds);
        }
    
        static void AllocateInLoop()
        {
            int x = 10;
    
            Stopwatch sw = Stopwatch.StartNew();
            int sum = 0;
            for (int i = 0; i < Iterations; i++)
            {
                sum += Apply(i, y => y + x);
            }
            sw.Stop();
            Console.WriteLine("Allocated in loop: {0}ms", sw.ElapsedMilliseconds);
        }
    
        static int Apply(int loopCounter, Func func)
        {
            return func(loopCounter);
        }
    }
    

    The compiler is smart, but there's still a difference. Using Reflector, we can see that AllocateInLoop is effectively compiled to:

    private static void AllocateInLoop()
    {
        Func func = null;
        int x = 10;
        Stopwatch stopwatch = Stopwatch.StartNew();
        int sum = 0;
        for (int i = 0; i < Iterations; i++)
        {
            if (func == null)
            {
                func = y => y + x;
            }
            sum += Apply(i, func);
        }
        stopwatch.Stop();
        Console.WriteLine("Allocated in loop: {0}ms", stopwatch.ElapsedMilliseconds);
    }
    

    So still only a single delegate instance is created, but there's extra logic within the loop - an extra nullity test on each iteration, basically.

    On my machine that makes about a 15% difference in performance.

提交回复
热议问题