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

一直知道ArrayList性能不太好,今天就来试了一下, 贴下来以后使用时做个参考.

请看下面的代码:

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

namespace Csharp.Test
{
    
public class Program
    {
        
public static void Main(string[] args)
        {
            var k 
= 1500000;

            Stopwatch stopWatch 
= new Stopwatch();
            stopWatch.Start();
            ArrayList arrayList 
= new ArrayList();
            
for (int i = 0; i < k; i++)
            {
                arrayList.Add(i);
            }
            
foreach (int Item in arrayList)
            {
                
            }
            stopWatch.Stop();
            Console.WriteLine(
"ArrayList所花的时间:" + stopWatch.ElapsedMilliseconds);


            stopWatch.Reset();
            stopWatch.Start();
            
int[] array = new int[k];
            
for (int i = 0; i < k; i++)
            {
                array[i] 
= i;
            }
            
foreach (int Item in array)
            {
 
            }
            stopWatch.Stop();
            Console.WriteLine(
"Array所花的时间:" + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            List
<int> listInt = new List<int>();
            
for (int i = 0; i < k; i++)
            {
                listInt.Add(i);
            }
            
foreach (int Item in listInt)
            {

            }
            stopWatch.Stop();
            Console.WriteLine(
"List所花的时间:" + stopWatch.ElapsedMilliseconds);
            stopWatch.Reset();

            Console.ReadLine();
        }
    }
}
复制代码

运行就可以看到,性能的区别的

ArrayList  360

Array  25

List<T>  60

从上面的结果可以看出, 360与25之让的差距. 不同项目不同需求, 小项目用ArrayList 能使工作简单,  用也是可以的,  只是做个测试, 并不是排挤, 毕竟微软还是把它做出来了. 所以建议尽量使用Array, 因为往ArrayList里面添加和修改元素,都会引起装箱和拆箱的操作,频繁的操作可能会影响一部分效率。

 

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