随笔 - 163  文章 - 2  评论 - 370  阅读 - 46万 

ArrayList是在System.Collections命名空间的一个类, 通过Add的方法添加一个项, 当进到这个类的元数据时, 可以看到这个方法的参数是一个object

 public virtual int Add(object value)

所以在添加一个项时需要进行一次装箱的操作, 读取一个数据时需要一个拆箱的操作, 所以用ArrayList必然影响性能, 特别是项较多的时候进行读写, 至少要进行一次的装箱一次拆箱, 所花的时候也应该是更多

 

 List<T>通过Add方法添加一个项是通过直接的类型来添加 public void Add(T item) 所以不需要再进行装箱与拆箱, 可以节省部分时间, 看下面的代码测试:

 

复制代码
代码
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ConsoleTest
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
//ArrayList
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ArrayList List1 
= new ArrayList();
            
for (int i = 0; i < 10000; i++)
            {
                List1.Add(i);
            }
            Console.WriteLine(
"Add item done.");
            
foreach (int item in List1)
            {
 
            }
            Console.WriteLine(
"Foreach item done.");
            sw.Stop();
            Console.WriteLine(
"ArrayList is need time:" + sw.ElapsedMilliseconds.ToString());

            
//List<int>
            sw.Reset();
            List
<int> List2 = new List<int>();
            
for (int i = 0; i < 10000; i++)
            {
                List2.Add(i);
            }
            Console.WriteLine(
"Add item done.");
            
foreach (int item in List2)
            {

            }
            Console.WriteLine(
"Foreach item done.");
            sw.Stop();
            Console.WriteLine(
"List<int> is need time:" + sw.ElapsedMilliseconds.ToString());
            Console.ReadLine();
        }
    }
}
复制代码

 

 

当你运行看结果时你就知道相差的结果了, 所以在代码当中, 尽量使用List<int>来代替ArrayList

 

 

 

 

posted on   风浪  阅读(633)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示