ArrayList與List筆記

來源:互聯網
上載者:User

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();
        }
    }
}

 

 

當你運行看結果時你就知道相差的結果了, 所以在代碼當中, 盡量使用List<int>來代替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.