最近在看《CLR via C#》,有關(guān)泛型的優(yōu)勢(shì),,感覺(jué)說(shuō)的挺不錯(cuò)的特記錄一下,,以供以后查看,。
泛型為開(kāi)發(fā)人員提供的優(yōu)勢(shì):
為了理解泛型的優(yōu)勢(shì),寫(xiě)了一個(gè)程序來(lái)比較泛型List算法和FCL的非泛型ArrayList算法的性能,。同時(shí)使用值類型和引用類型的對(duì)象來(lái)測(cè)試這兩個(gè)算法的性能: static void Main(string[] args) { ValueTypePerfTest(); ReferenceTypePerfTest(); Console.ReadLine(); } public static void ValueTypePerfTest() { const Int32 count = 10000000; using (new OperationTimer("List<Int32>")) { List<Int32> l = new List<Int32>(count); for (Int32 i = 0; i < count; i++) { l.Add(i); Int32 x = l[i]; } l = null; } using (new OperationTimer("ArrayList of Int32")) { ArrayList a = new ArrayList(); for (Int32 i = 0; i < count; i++) { a.Add(i); Int32 x = (Int32)a[i]; } a = null; } } public static void ReferenceTypePerfTest() { const Int32 count = 10000000; using (new OperationTimer("List<string>")) { List<string> l = new List<string>(); for (Int32 i = 0; i < count; i++) { l.Add("X"); string x = l[i]; } l = null; } using (new OperationTimer("ArrayList of string")) { ArrayList a = new ArrayList(); for (Int32 i = 0; i < count; i++) { a.Add("X"); string x = (String)a[i]; } a = null; } Console.ReadLine(); } } internal sealed class OperationTimer : IDisposable { private Int64 m_startTime; private string m_text; private Int32 m_collectionount; public OperationTimer(string text) { PrepareForOperation(); m_text = text; m_collectionount = GC.CollectionCount(0); m_startTime = Stopwatch.GetTimestamp(); } public void Dispose() { Console.WriteLine("{0,6:###.00} seconds (GCs={1,3}) {2}", (Stopwatch.GetTimestamp()-m_startTime)/(Double)Stopwatch.Frequency, GC.CollectionCount(0)-m_collectionount,m_text); } private static void PrepareForOperation() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }
這個(gè)輸出結(jié)果證明:將泛型list算法應(yīng)用于Int32類型,,速度比將非泛型ArrayList算法應(yīng)用于Int32快的多,用ArrayList來(lái)操作值類型(Int32),,會(huì)造成大量裝箱操作,,最終要進(jìn)行44次垃圾回收次數(shù)(GC)。相應(yīng)地,,List算法需要的垃圾回收次數(shù)是0,。使用引用類型來(lái)測(cè)試,差別就沒(méi)有那么明顯了,。 |
|
來(lái)自: 昵稱10504424 > 《C#》