ArrayList Array List效能比較

來源:互聯網
上載者:User

一直知道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裡面添加和修改元素,都會引起裝箱和拆箱的操作,頻繁的操作可能會影響一部分效率。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.