C# interface與delegate效能比較的深入解析
更新時間:2013年05月31日 10:53:28 作者:
本篇文章是對C#中interface與delegate的效能比較進行了詳細(xì)的分析介紹,需要的朋友參考下
前言
以前在Code Complete 2nd(代碼大全2)這本書上看過
說在像是C#這種類型語言中能不要用delegate就盡量不要用,多使用interface取代,以避免效能上的影響
實踐出真理,所以我就寫了個小范例來測試
我的硬件是2.66G 4核心CPU,內(nèi)存4G
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;
}
}
}
以前在Code Complete 2nd(代碼大全2)這本書上看過
說在像是C#這種類型語言中能不要用delegate就盡量不要用,多使用interface取代,以避免效能上的影響
實踐出真理,所以我就寫了個小范例來測試
我的硬件是2.66G 4核心CPU,內(nèi)存4G

我不知道是不是電腦比較快,以及我寫的函數(shù)太小的關(guān)系
次數(shù)到了10000000次才看到有影響

到了100000000次后看起來也是還好
總而分析,還是會有影響
需要高效運算或是在嵌入式中,應(yīng)該還是要多注意一點
代碼
復(fù)制代碼 代碼如下:
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;
}
}
}
相關(guān)文章
詳解C語言中的ttyname()函數(shù)和isatty()函數(shù)的用法
這篇文章主要介紹了C語言中的ttyname()函數(shù)和isatty()函數(shù)的用法,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
C++數(shù)據(jù)結(jié)構(gòu)哈希表詳解
C++標(biāo)準(zhǔn)庫中使用的unordered_map底層實現(xiàn)是哈希表,下面這篇文章主要給大家介紹了關(guān)于C++中使用哈希表(unordered_map)的一些常用操作方法,需要的朋友可以參考下2022-07-07

