static void Main(string[] args){ Stopwatch sw = new Stopwatch(); int[] intArray = new int[100]; sw.Start(); for (int i = 0; i < 100; i++) { intArray[i] = i; } sw.Stop(); Console.WriteLine(" Add 0 ~ 100 to int[100] : " + sw.Elapsed); ArrayList list = new ArrayList(); sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100; i++) { list.Add(i); } sw.Stop(); Console.WriteLine(" Add 0 ~ 100 to ArrayList : " + sw.Elapsed); List intList = new List (); sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100; i++) { intList.Add(i); } sw.Stop(); Console.WriteLine(" Add 0 ~ 100 to List : " + sw.Elapsed); Console.ReadLine();}
效果如图:
可以看到数组明显比较快,但是必需初始化长度
目测原因是往ArrayList中添加元素时发生了装箱操作