• 【C#食谱】【面食】菜单3:用泛型替代ArrayList


    问题:

    你希望用泛型替代所有的ArrayList以提高应用程序的性能,并使代码更简单。当你发现结构体或其他类型的值保存在这些数据结构中,导致装箱/拆箱操作时,这个是必要的。

    解决方法:

    把所有出现System.Collections.ArrayList的类用效能更好的泛型System.Collections.Generic.List类替代。

    这里有一个用System.Collections.ArrayList类的简单的例子:


        public static void UseNonGenericArrayList()
        
    {
            
    // Create and populate an ArrayList.
            ArrayList numbers = new ArrayList();
            numbers.Add(
    1); // Causes a boxing operation to occur
            numbers.Add(2); // Causes a boxing operation to occur

            
    // Display all integers in the ArrayList.    
            
    // Causes an unboxing operation to occur on each iteration
            foreach (int i in numbers)
            
    {
                Console.WriteLine(i);
            }


            numbers.Clear();
        }

    这里是一个用System.Collections.Generic.List的简单例子:


        public static void UseGenericList()
        
    {
            
    // Create and populate a List.
            List<int> numbers = new List<int>();
            numbers.Add(
    1);
            numbers.Add(
    2);

            
    // Display all integers in the ArrayList.
            foreach (int i in numbers)
            
    {
                Console.WriteLine(i);
            }


            numbers.Clear();
        }

    讨论:

    由于ArrayList几乎在所有的应用程序中都会用到,因此,这是第一个可以改善性能的好地方。在一些简单的应用程序中,用这种替代方法实现ArrayList是非常简单的。但是,有几点是应该值得注意的。比如,泛型List类并没有实现ICloneable接口,而ArrayList类实现了。

    注意,如果没有返回一个同步版本的泛型List,没有返回确定大小的泛型List,那么IsFixedSizeIsSynchronized属性将始终返回falseSyncRoot属性将始终返回一个和它相同的对象。实际上,这个属性返回的是this指针。微软建议,使用lock关键字去锁定整个集合或者是其他你使用的同步的对象。

    PSArrayList默认的构建大小是16个元素,而List<T>4个元素。也就是说,如果第17个元素被加到List<T>中,那么,List<T>会重新分配大小3次;而ArrayList只需1次。对于程序的性能,这一点是应该考虑的。


    新年就要到了,祝大家新春愉快! 

  • 相关阅读:
    MD5加密
    input text 只能输入数字
    input date 支持placeholder属性
    实例表单的增改删
    jQuery 框架中$.ajax()的常用参数有哪些?
    jquery的相关属性和方法
    JS中实现继承的六种方式及优缺点
    c++类型转换
    c++动态内存与智能指针
    c++类的构造函数
  • 原文地址:https://www.cnblogs.com/adaiye/p/1061675.html
Copyright © 2020-2023  润新知