C# interface与delegate效能比较的深入解析_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

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

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

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



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

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598