編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20)
軟件開發(fā)過程中,不可避免會用到集合,C#中的集合表現(xiàn)為數(shù)組和若干集合類。不管是數(shù)組還是集合類,它們都有各自的優(yōu)缺點。如何使用好集合是我們在開發(fā)過程中必須掌握的技巧。不要小看這些技巧,一旦在開發(fā)中使用了錯誤的集合或針對集合的方法,應用程序?qū)畴x你的預想而運行。
建議20:使用泛型集合代替非泛型集合
在建議1中我們知道,如果要讓代碼高效運行,應該盡量避免裝箱和拆箱,以及盡量減少轉(zhuǎn)型。很遺憾,在微軟提供給我們的第一代集合類型中沒有做到這一點,下面我們看ArrayList這個類的使用情況:
ArrayList al=new ArrayList(); al.Add(0); al.Add(1); al.Add("mike"); foreach (var item in al) { Console.WriteLine(item); }
上面這段代碼充分演示了我們可以將程序?qū)懙枚嗝丛愀狻?/p>
首先,ArrayList的Add方法接受一個object參數(shù),所以al.Add(1)首先會完成一次裝箱;其次,在foreach循環(huán)中,待遍歷到它時,又將完成一次拆箱。
在這段代碼中,整形和字符串作為值類型和引用類型,都會先被隱式地強制轉(zhuǎn)型為object,然后在foreach循環(huán)中又被轉(zhuǎn)型回來。
同時,這段代碼也是非類型安全的:我們?nèi)籄rrayList同時存儲了整型和字符串,但是缺少編譯時的類型檢查。雖然有時候需要有意這樣去實現(xiàn),但是更多的時候,應該盡量避免。缺少類型檢查,在運行時會帶來隱含的Bug。集合類ArrayList如果進行如下所示的運算,就會拋出一個IvalidCastException:
ArrayList al=new ArrayList(); al.Add(0); al.Add(1); al.Add("mike"); int t = 0; foreach (int item in al) { t += item; }
ArrayList同時還提供了一個帶ICollection參數(shù)的構(gòu)造方法,可以直接接收數(shù)組,如下所示:
var intArr = new int[] {0, 1, 2, 3}; ArrayList al=new ArrayList(intArr);
該方法內(nèi)部實現(xiàn)一樣糟糕,如下所示(構(gòu)造方法內(nèi)部最終調(diào)用了下面的InsertRange方法):
public virtual void InsertRange(int index, ICollection c) { if (c == null) { throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection")); } if ((index < 0) || (index > this._size)) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } int count = c.Count; if (count > 0) { this.EnsureCapacity(this._size + count); if (index < this._size) { Array.Copy(this._items, index, this._items, index + count, this._size - index); } object[] array = new object[count]; c.CopyTo(array, 0); array.CopyTo(this._items, index); this._size += count; this._version++; } }
概括來講,如果對大型集合進行循環(huán)訪問、轉(zhuǎn)型或裝箱和拆箱操作,使用ArrayList這樣的傳統(tǒng)集合對效率影響會非常大。鑒于此,微軟提供了對泛型的支持。泛型使用一對<>括號將實際類型括起來,然后編譯器和運行時會完成剩余的工作。微軟也不建議大家使用ArrayList這樣的類型了,轉(zhuǎn)而建議使用它們的泛型實現(xiàn),如List<T>。
注意,非泛型集合在System.Collections命名空間下,對應的泛型集合則在System.Collections.Generic命名空間下。
建議一開始的那段代碼的泛型實現(xiàn)為:
List<int> intList = new List<int>(); intList.Add(1); intList.Add(2); //intList.Add("mike"); foreach (var item in intList) { Console.WriteLine(item); }
代碼中被注釋的那一行不會被編譯通過,因為“mike"不是整型,這里就體現(xiàn)了類型安全的特點。
下面比較了非泛型集合和泛型集合在運行中的效率:
static void Main(string[] args) { Console.WriteLine("開始測試ArrayList:"); TestBegin(); TestArrayList(); TestEnd(); Console.WriteLine("開始測試List<T>:"); TestBegin(); TestGenericList(); TestEnd(); } static int collectionCount = 0; static Stopwatch watch = null; static int testCount = 10000000; static void TestBegin() { GC.Collect(); //強制對所有代碼進行即時垃圾回收 GC.WaitForPendingFinalizers(); //掛起線程,執(zhí)行終結(jié)器隊列中的終結(jié)器(即析構(gòu)方法) GC.Collect(); //再次對所有代碼進行垃圾回收,主要包括從終結(jié)器隊列中出來的對象 collectionCount = GC.CollectionCount(0); //返回在0代碼中執(zhí)行的垃圾回收次數(shù) watch = new Stopwatch(); watch.Start(); } static void TestEnd() { watch.Stop(); Console.WriteLine("耗時:" + watch.ElapsedMilliseconds.ToString()); Console.WriteLine("垃圾回收次數(shù):" + (GC.CollectionCount(0) - collectionCount)); } static void TestArrayList() { ArrayList al = new ArrayList(); int temp = 0; for (int i = 0; i < testCount; i++) { al.Add(i); temp = (int)al[i]; } al = null; } static void TestGenericList() { List<int> listT = new List<int>(); int temp = 0; for (int i = 0; i < testCount; i++) { listT.Add(i); temp = listT[i]; } listT = null; }
輸出為:
開始測試ArrayList:
耗時:2375
垃圾回收次數(shù):26
開始測試List<T>:
耗時:220
垃圾回收次數(shù):5
以上介紹了編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20),有關(guān)編寫高質(zhì)量代碼建議1到建議157,本完整會持續(xù)更新,敬請關(guān)注,謝謝。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。