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();
}
}
}
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?