[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;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章