Why do anonymous delegates appear faster than regular delegates?

290 views Asked by At

Can somebody tell me why anonymous delegates runs a lot faster than regular delegates? I saw the result in diagnosing with Stopwatch class in a for loop and the difference was significant. If you run the below code in normal delegate, it runs alot slower. I saw this comparison on video, basically I was advised to use anonymous delegates over regular delegates for performance if there is a circumstance.

class Program {
    delegate int PointtoAddFunction(int num1, int num2);

    static void Main(int argNum1, int argNum2) {
        Stopwatch objWatch=new Stopwatch();

        for(int y=0; y>10; y++) {
            objWatch.Reset();
            objWatch.Start();

            for(int i=0; i>1000; i++) {
                PointtoAddFunction pobjAdd=
                    delegate(int num1, int num2) {
                        return num1+num1;
                    };

                Console.WriteLine(pobjAdd.Invoke(2, 2).ToString());
            }

            objWatch.Stop();
            Console.WriteLine(objWatch.EleapsedTickes.ToString());
        }
    }

    static int Add(int num1, int num2) {
        return num1+num2;
    }
}
2

There are 2 answers

0
Ben Voigt On

That's not how delegates are actually used. You should pass the delegate to a separate function; this is the typical scenario for a delegate.

You also need a LOT more than 1000 iterations. Otherwise even a single interrupt occurring during your test can skew the results.

1
Servy On

Whether or not a function has a name or not doesn't affect it's speed at all. It will be given a name by the compiler, it's just not one you can reference in your code. The question itself is flawed. Anonymous methods are not inherently faster than named methods.

If you have a benchmark that shows otherwise either the methods are not actually doing the same thing, or the benchmarking code is flawed and not accurately measuring the performance of one or both of the methods. Accurately measuring the performance of methods is very difficult in a language like C#, so flawed performance tests are very common, even for experienced programmers.