泛型實現了一種型別安全的演算法重用,其最直接的應用正是在集合類中的效能與安全的良好體現,因此建議以泛型集合來代替非泛型集合。
下面以 List<T> 來說明,針對不同的資料類型(class,string,int)使用非泛型集合與使用泛型集合的程式效能差別。
(由於非泛型集合支援的參數類型為object,因此為了保證可比性,本文以List<object> 來代替非泛型集合。)
using System;using System.Collections.Generic;using System.Text;using System.Collections;using System.Diagnostics;namespace Test_Console{ class Program10 { static void Main(string[] args) { Perf perf; testClass tc = new testClass(5); perf = new Perf(); perf.PerfCompare<testClass>(tc); perf = null; string str = "newStr"; perf = new Perf(); perf.PerfCompare<string>(str); perf = null; int i = 2010; perf = new Perf(); perf.PerfCompare<int>(i); perf = null; } } class Perf34 { public void PerfCompare<T>(T testObj) { List<object> listObject = new List<object>(); List<T> listT = new List<T>(); long ms = 0; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { listObject.Add(testObj); } sw.Stop(); ms = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int i = 0; i < 1000000; i++) { listT.Add(testObj); } sw.Stop(); Console.WriteLine("Compare Between [{0}] And [{1}]:", "object", testObj.GetType()); Console.WriteLine(ms + " : " + sw.ElapsedMilliseconds); Console.WriteLine(); } } class testClass { int testInt; public testClass(int i) { testInt = i; } }}
運行結果如下:
由於testClass和string類型均為參考型別,因此,使用非泛型集合不需經過裝箱過程,程式執行差別不大;
而對於int類型,若使用非泛型集合則需要經過裝箱拆箱過程,故使用泛行集合會大大提高運行效率。