[C#] interface与delegate的效能比较

前言

以前在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;
        }
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值