C# interface与delegate效能比较的深入解析

前言
以前在Code Complete 2nd(代码大全2)这本书上看过
说在像是C#这种类型语言中能不要用delegate就尽量不要用,多使用interface取代,以避免效能上的影响
实践出真理,所以我就写了个小范例来测试
我的硬件是2.66G 4核心CPU,内存4G

C# interface与delegate效能比较的深入解析

我不知道是不是电脑比较快,以及我写的函数太小的关系
次数到了10000000次才看到有影响

C# interface与delegate效能比较的深入解析

到了100000000次后看起来也是还好
总而分析,还是会有影响
需要高效运算或是在嵌入式中,应该还是要多注意一点
代码

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Performance
{
    class Program
    {
        delegate int Add(int a, int b);
        static Add myDelegate;
        const int LOOP_COUNT = 100000000;
        static void Main(string[] args)
        {
            myDelegate = new Add(TestAdd);
            IOrz orz = new Orz();
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                int c = orz.DoIt(1, 2);
            }
            st.Stop();
            Console.WriteLine(" Call Interface Elapsed time:{0} ms", st.ElapsedMilliseconds);
            st.Reset();
            st.Start();
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                int d = myDelegate(3, 5);
            }
            st.Stop();
            Console.WriteLine("Call Delegate Elapsed time :{0} ms", st.ElapsedMilliseconds);
            Console.ReadLine();
        }
        static int TestAdd(int a, int b)
        {
            int c = a + b;
            return c;
        }
    }
}