軟件開(kāi)發(fā)過(guò)程中,不可避免會(huì)用到集合,C#中的集合表現(xiàn)為數(shù)組和若干集合類(lèi)。不管是數(shù)組還是集合類(lèi),它們都有各自的優(yōu)缺點(diǎn)。如何使用好集合是我們?cè)陂_(kāi)發(fā)過(guò)程中必須掌握的技巧。不要小看這些技巧,一旦在開(kāi)發(fā)中使用了錯(cuò)誤的集合或針對(duì)集合的方法,應(yīng)用程序?qū)?huì)背離你的預(yù)想而運(yùn)行。
建議20:使用泛型集合代替非泛型集合
在建議1中我們知道,如果要讓代碼高效運(yùn)行,應(yīng)該盡量避免裝箱和拆箱,以及盡量減少轉(zhuǎn)型。很遺憾,在微軟提供給我們的第一代集合類(lèi)型中沒(méi)有做到這一點(diǎn),下面我們看ArrayList這個(gè)類(lèi)的使用情況:
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方法接受一個(gè)object參數(shù),所以al.Add(1)首先會(huì)完成一次裝箱;其次,在foreach循環(huán)中,待遍歷到它時(shí),又將完成一次拆箱。
在這段代碼中,整形和字符串作為值類(lèi)型和引用類(lèi)型,都會(huì)先被隱式地強(qiáng)制轉(zhuǎn)型為object,然后在foreach循環(huán)中又被轉(zhuǎn)型回來(lái)。
同時(shí),這段代碼也是非類(lèi)型安全的:我們?nèi)籄rrayList同時(shí)存儲(chǔ)了整型和字符串,但是缺少編譯時(shí)的類(lèi)型檢查。雖然有時(shí)候需要有意這樣去實(shí)現(xiàn),但是更多的時(shí)候,應(yīng)該盡量避免。缺少類(lèi)型檢查,在運(yùn)行時(shí)會(huì)帶來(lái)隱含的Bug。集合類(lèi)ArrayList如果進(jìn)行如下所示的運(yùn)算,就會(huì)拋出一個(gè)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同時(shí)還提供了一個(gè)帶ICollection參數(shù)的構(gòu)造方法,可以直接接收數(shù)組,如下所示:
var intArr = new int[] {0, 1, 2, 3};
ArrayList al=new ArrayList(intArr);
該方法內(nèi)部實(shí)現(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++;
}
}
概括來(lái)講,如果對(duì)大型集合進(jìn)行循環(huán)訪問(wèn)、轉(zhuǎn)型或裝箱和拆箱操作,使用ArrayList這樣的傳統(tǒng)集合對(duì)效率影響會(huì)非常大。鑒于此,微軟提供了對(duì)泛型的支持。泛型使用一對(duì)>括號(hào)將實(shí)際類(lèi)型括起來(lái),然后編譯器和運(yùn)行時(shí)會(huì)完成剩余的工作。微軟也不建議大家使用ArrayList這樣的類(lèi)型了,轉(zhuǎn)而建議使用它們的泛型實(shí)現(xiàn),如ListT>。
注意,非泛型集合在System.Collections命名空間下,對(duì)應(yīng)的泛型集合則在System.Collections.Generic命名空間下。
建議一開(kāi)始的那段代碼的泛型實(shí)現(xiàn)為:
Listint> intList = new Listint>();
intList.Add(1);
intList.Add(2);
//intList.Add("mike");
foreach (var item in intList)
{
Console.WriteLine(item);
}
代碼中被注釋的那一行不會(huì)被編譯通過(guò),因?yàn)椤癿ike"不是整型,這里就體現(xiàn)了類(lèi)型安全的特點(diǎn)。
下面比較了非泛型集合和泛型集合在運(yùn)行中的效率:
static void Main(string[] args)
{
Console.WriteLine("開(kāi)始測(cè)試ArrayList:");
TestBegin();
TestArrayList();
TestEnd();
Console.WriteLine("開(kāi)始測(cè)試ListT>:");
TestBegin();
TestGenericList();
TestEnd();
}
static int collectionCount = 0;
static Stopwatch watch = null;
static int testCount = 10000000;
static void TestBegin()
{
GC.Collect(); //強(qiáng)制對(duì)所有代碼進(jìn)行即時(shí)垃圾回收
GC.WaitForPendingFinalizers(); //掛起線程,執(zhí)行終結(jié)器隊(duì)列中的終結(jié)器(即析構(gòu)方法)
GC.Collect(); //再次對(duì)所有代碼進(jìn)行垃圾回收,主要包括從終結(jié)器隊(duì)列中出來(lái)的對(duì)象
collectionCount = GC.CollectionCount(0); //返回在0代碼中執(zhí)行的垃圾回收次數(shù)
watch = new Stopwatch();
watch.Start();
}
static void TestEnd()
{
watch.Stop();
Console.WriteLine("耗時(shí):" + 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;
}
輸出為:
開(kāi)始測(cè)試ArrayList:
耗時(shí):2375
垃圾回收次數(shù):26
開(kāi)始測(cè)試ListT>:
耗時(shí):220
垃圾回收次數(shù):5
以上介紹了編寫(xiě)高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20),有關(guān)編寫(xiě)高質(zhì)量代碼建議1到建議157,本完整會(huì)持續(xù)更新,敬請(qǐng)關(guān)注,謝謝。
您可能感興趣的文章:- C#泛型概念的簡(jiǎn)介與泛型的使用
- C#泛型類(lèi)創(chuàng)建與使用的方法
- 深入解析C#編程中泛型委托的使用
- 簡(jiǎn)單學(xué)習(xí)C#中的泛型方法使用
- 詳解C#中的泛型以及編程中使用泛型的優(yōu)點(diǎn)
- C#泛型集合DictionaryK,V>的使用方法
- 介紹C# 泛型類(lèi)在使用中約束
- C#泛型的使用及示例詳解