软件开发过程中,不可避免会用到集合,C#中的集合表现为数组和若干集合类。不管是数组还是集合类,它们都有各自的优缺点。如何使用好集合是我们在开发过程中必须掌握的技巧。不要小看这些技巧,一旦在开发中使用了错误的集合或针对集合的方法,应用程序将会背离你的预想而运行。

建议20:使用泛型集合代替非泛型集合

在建议1中我们知道,如果要让代码高效运行,应该尽量避免装箱和拆箱,以及尽量减少转型。很遗憾,在微软提供给我们的第一代集合类型中没有做到这一点,下面我们看ArrayList这个类的使用情况:

  ArrayList al=new ArrayList();      al.Add(0);      al.Add(1);      al.Add("mike");      foreach (var item in al)      {        Console.WriteLine(item);      }

首先,ArrayList的Add方法接受一个object参数,所以al.Add(1)首先会完成一次装箱;其次,在foreach循环中,待遍历到它时,又将完成一次拆箱。

在这段代码中,整形和字符串作为值类型和引用类型,都会先被隐式地强制转型为object,然后在foreach循环中又被转型回来。

同时,这段代码也是非类型安全的:我们然ArrayList同时存储了整型和字符串,但是缺少编译时的类型检查。虽然有时候需要有意这样去实现,但是更多的时候,应该尽量避免。缺少类型检查,在运行时会带来隐含的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;      }
var intArr = new int[] {0, 1, 2, 3};ArrayList al=new ArrayList(intArr);

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++;  }}

注意,非泛型集合在System.Collections命名空间下,对应的泛型集合则在System.Collections.Generic命名空间下。

建议一开始的那段代码的泛型实现为:

List<int> intList = new List<int>();      intList.Add(1);      intList.Add(2);      //intList.Add("mike");      foreach (var item in intList)      {        Console.WriteLine(item);      }

下面比较了非泛型集合和泛型集合在运行中的效率:

 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(); //挂起线程,执行终结器队列中的终结器(即析构方法)      GC.Collect();  //再次对所有代码进行垃圾回收,主要包括从终结器队列中出来的对象      collectionCount = GC.CollectionCount(0);  //返回在0代码中执行的垃圾回收次数      watch = new Stopwatch();      watch.Start();    }    static void TestEnd()    {      watch.Stop();      Console.WriteLine("耗时:" + watch.ElapsedMilliseconds.ToString());      Console.WriteLine("垃圾回收次数:" + (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

垃圾回收次数:26

开始测试List<T>:

耗时:220

垃圾回收次数:5

更多相关文章

  1. android EditText设置不可写
  2. android 使用html5作布局文件: webview跟javascript交互
  3. android studio调试c/c++代码
  4. IM-A820L限制GSM,WCDMA上网的原理(其他泛泰机型可参考)7.13
  5. 锁屏界面
  6. android(NDK+JNI)---Eclipse+CDT+gdb调试android ndk程序
  7. Android(安卓)version and Linux Kernel version
  8. Android(安卓)闹钟管理类的使用
  9. Android学习篇之Menu的使用

随机推荐

  1. 内网主机从外面连接不了?SSH反向隧道来帮
  2. Scrapy框架的使用之Spider的用法
  3. Scrapy框架的使用之Scrapy入门
  4. 记一次网络中断故障处理
  5. 【机器学习笔记】:大话线性回归(二)
  6. 【机器学习笔记】:一文让你彻底记住什么是
  7. 【SQL刷题系列】:leetcode178 Rank Scores
  8. 谁才是权游的真正主角。
  9. Scrapy框架的使用之Downloader Middlewar
  10. 【SQL刷题系列】:leetcode183 Customers W