时间:2021-07-01 10:21:17 帮助过:56人阅读
软件开发过程中,不可避免会用到集合,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;
- }
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#程序——使用泛型集合代替非泛型集合(建议20),有关编写高质量代码建议1到建议157,本完整会持续更新,敬请关注,谢谢。