三、用泛型替代ArrayList

來源:互聯網
上載者:User
問題:

你希望用泛型替代所有的ArrayList以提高應用程式的效能,並使代碼更簡單。當你發現結構體或其他類型的值儲存在這些資料結構中,導致裝箱/拆箱操作時,這個是必要的。

解決方案:

把所有出現System.Collections.ArrayList的類用效能更好的泛型System.Collections.Generic.List類替代。

這裡有一個用System.Collections.ArrayList類的簡單的例子:

    public static void UseNonGenericArrayList()
    {
        // Create and populate an ArrayList.
        ArrayList numbers = new ArrayList();
        numbers.Add(1); // Causes a boxing operation to occur
        numbers.Add(2); // Causes a boxing operation to occur

        // Display all integers in the ArrayList.    
        // Causes an unboxing operation to occur on each iteration
        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }

        numbers.Clear();
    }

這裡是一個用System.Collections.Generic.List的簡單例子:

    public static void UseGenericList()
    {
        // Create and populate a List.
        List<int> numbers = new List<int>();
        numbers.Add(1);
        numbers.Add(2);

        // Display all integers in the ArrayList.
        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }

        numbers.Clear();
    }

討論:

由於ArrayList幾乎在所有的應用程式中都會用到,因此,這是第一個可以改善效能的好地方。在一些簡單的應用程式中,用這種替代方法實現ArrayList是非常簡單的。但是,有幾點是應該值得注意的。比如,泛型List類並沒有實現ICloneable介面,而ArrayList類實現了。

注意,如果沒有返回一個同步版本的泛型List,沒有返回確定大小的泛型List,那麼IsFixedSize和IsSynchronized屬性將始終返回false。SyncRoot屬性將始終返回一個和它相同的對象。實際上,這個屬性返回的是this指標。微軟建議,使用lock關鍵字去鎖定整個集合或者是其他你使用的同步的對象。

PS:ArrayList預設的構建大小是16個元素,而List<T>是4個元素。也就是說,如果第17個元素被加到List<T>中,那麼,List<T>會重新分配大小3次;而ArrayList只需1次。對於程式的效能,這一點是應該考慮的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.