Array,ArrayList,List,Dictionary是比较常用的集合,今天突发奇想,看看这几个的差别大不大,尽管之前看过对这几个的比较,自己实操下也加深理解吧。贴出代码和结果作为笔记。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConApp
{
class Program
{
static void Main(string[] args)
{
Stopwatch s1 = new Stopwatch();
s1.Start();
int[] a = new int[10000000];
for (int i = 0; i < 10000000; i++)
{
a[i] = i;
}
s1.Stop();
Console.WriteLine("数组int[]用时:{0}毫秒", s1.ElapsedMilliseconds);
Stopwatch s2 = new Stopwatch();
s2.Start();
ArrayList b = new ArrayList();
for (int i = 0; i < 10000000; i++)
{
b.Add(i);
}
s2.Stop();
Console.WriteLine("集合ArrayList用时:{0}毫秒", s2.ElapsedMilliseconds);
Stopwatch s3 = new Stopwatch();
s3.Start();
List<int> c = new List<int>();
for (int i = 0; i < 10000000; i++)
{
c.Add(i);
}
s3.Stop();
Console.WriteLine("集合List用时:{0}毫秒", s3.ElapsedMilliseconds);
Stopwatch s4 = new Stopwatch();
s4.Start();
Dictionary<int, int> d = new Dictionary<int, int>();
for (int i = 0; i < 10000000; i++)
{
d.Add(i, i);
}
s4.Stop();
Console.WriteLine("集合List用时:{0}毫秒", s4.ElapsedMilliseconds);
Console.Read();
}
}
}
可能每次运行结果会有误差,但大致也能看出对应的结果。