泛型为开发人员提供的优势:
为了理解泛型的优势,写了一个程序来比较泛型List算法和FCL的非泛型ArrayList算法的性能。同时使用值类型和引用类型的对象来测试这两个算法的性能:
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();}
输出结果如下:
这个输出结果证明:将泛型list算法应用于Int32类型,速度比将非泛型ArrayList算法应用于Int32快的多,用ArrayList来操作值类型(Int32),会造成大量装箱操作,最终要进行44次垃圾回收次数(GC)。相应地,List算法需要的垃圾回收次数是0。使用引用类型来测试,差别就没有那么明显了。
联系客服