惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
小众软件
小众软件
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
B
Blog
量子位
B
Blog RSS Feed
Vercel News
Vercel News
Blog — PlanetScale
Blog — PlanetScale
Last Week in AI
Last Week in AI
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
爱范儿
爱范儿
Jina AI
Jina AI
C
Check Point Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
H
Hackread – Cybersecurity News, Data Breaches, AI and More
云风的 BLOG
云风的 BLOG

博客园 - Net_Learner

ASP.NET2.0 Provider模型(上) ——原理、模型与分析 浅析PetShop程序中的购物车和订单处理模块(Profile技术,异步MSMQ消息) PetShop数据库解读 petshop里的product.aspx页面详解 PetShop的工厂模式 PetShop之表示层设计 PetShop之业务逻辑层设计 PetShop之ASP.NET缓存 PetShop数据访问层之消息处理 PetShop数据访问层之数据库访问设计 PetShop的系统架构设计[转] Microsoft .NET Pet Shop 4 架构与技术分析 NET设计模式(3): 抽象工厂模式 NET设计模式(2): 工厂方法模式 NET设计模式(1): 简单工厂模式 七、用默认值初始化泛型变量 六、泛型约束 五、用泛型副本替换哈希表 四、List和LinkedList性能比较 二、理解泛型
三、用泛型替代ArrayList
Net_Learner · 2008-07-24 · via 博客园 - Net_Learner

问题:

你希望用泛型替代所有的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次。对于程序的性能,这一点是应该考虑的。