星空网 > 软件开发 > ASP.net

编写高质量代码改善C#程序的157个建议——建议20:使用泛型集合代替非泛型集合

建议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;      }

ArrayList同时还提供了一个带ICollection参数的构造方法,可以直接接收数组,如下所示:

var intArr = new int[] {0, 1, 2, 3};ArrayList al=new ArrayList(intArr);

该方法内部实现一样糟糕,如下所示(构造方法内部最终调用了下面的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++;  }} 

概括来讲,如果对大型集合进行循环访问、转型或装箱和拆箱操作,使用ArrayList这样的传统集合对效率影响会非常大。鉴于此,微软提供了对泛型的支持。泛型使用一对<>括号将实际类型括起来,然后编译器和运行时会完成剩余的工作。微软也不建议大家使用ArrayList这样的类型了,转而建议使用它们的泛型实现,如List<T>。

注意,非泛型集合在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);      }

代码中被注释的那一行不会被编译通过,因为“mike"不是整型,这里就体现了类型安全的特点。

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

    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

 

 

转自:《编写高质量代码改善C#程序的157个建议》陆敏技




原标题:编写高质量代码改善C#程序的157个建议——建议20:使用泛型集合代替非泛型集合

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

巨量千川直播投放账户操作指南:https://www.kjdsnews.com/a/1444196.html
增长超80%!跨境电商在中东土豪的王国里淘金:https://www.kjdsnews.com/a/1444197.html
【Google Ads】谷歌广告投放常见问题详解(13):https://www.kjdsnews.com/a/1444198.html
TikTok“懒人锅”5天破1000万播放,“搓泥宝膏”获大量国外网友青睐:https://www.kjdsnews.com/a/1444199.html
外贸交易会常用语:https://www.kjdsnews.com/a/1444200.html
TikTok跨境MCN应如何申请?必看:https://www.kjdsnews.com/a/1444201.html
三亚有哪些酒店值得入住?:https://www.vstour.cn/a/366173.html
零售晚报:丽人丽妆2023年扭亏为盈 玉容初、美壹堂等自有品牌增速超40% :https://www.kjdsnews.com/a/1836649.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流