軟件開發(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ù)的構造方法,可以直接接收數(shù)組,如下所示:
var intArr = new int[] {0, 1, 2, 3};
ArrayList al=new ArrayList(intArr);
該方法內(nèi)部實現(xiàn)一樣糟糕,如下所示(構造方法內(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),如ListT>。
注意,非泛型集合在System.Collections命名空間下,對應的泛型集合則在System.Collections.Generic命名空間下。
建議一開始的那段代碼的泛型實現(xiàn)為:
Listint> intList = new Listint>();
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("開始測試ListT>:");
TestBegin();
TestGenericList();
TestEnd();
}
static int collectionCount = 0;
static Stopwatch watch = null;
static int testCount = 10000000;
static void TestBegin()
{
GC.Collect(); //強制對所有代碼進行即時垃圾回收
GC.WaitForPendingFinalizers(); //掛起線程,執(zhí)行終結器隊列中的終結器(即析構方法)
GC.Collect(); //再次對所有代碼進行垃圾回收,主要包括從終結器隊列中出來的對象
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()
{
Listint> listT = new Listint>();
int temp = 0;
for (int i = 0; i testCount; i++)
{
listT.Add(i);
temp = listT[i];
}
listT = null;
}
輸出為:
開始測試ArrayList:
耗時:2375
垃圾回收次數(shù):26
開始測試ListT>:
耗時:220
垃圾回收次數(shù):5
以上介紹了編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20),有關編寫高質(zhì)量代碼建議1到建議157,本完整會持續(xù)更新,敬請關注,謝謝。
您可能感興趣的文章:- C#泛型概念的簡介與泛型的使用
- C#泛型類創(chuàng)建與使用的方法
- 深入解析C#編程中泛型委托的使用
- 簡單學習C#中的泛型方法使用
- 詳解C#中的泛型以及編程中使用泛型的優(yōu)點
- C#泛型集合DictionaryK,V>的使用方法
- 介紹C# 泛型類在使用中約束
- C#泛型的使用及示例詳解