C#中List與Dictionary內存佔用對比

using System;
using System.Collections.Generic;

class Example
{
    static void Main(string[] args)
    {
        Example example = new Example();

        CarProfiler.BeginSample();
        //example.ListTest();
        example.DictionaryTest();
        CarProfiler.EndSample();
        CarProfiler.LogElapsedTicks();
        CarDebug.Info(GC.GetTotalMemory(false));


        Console.Read();
    }

    private List<List<int>> mListList = new List<List<int>>();
    private List<Dictionary<int, int>> mDictionaryList = new List<Dictionary<int, int>>();

    public void ListTest()
    {
        for (int i = 0; i < 10000; ++i)
        {
            mListList.Add(new List<int>());
        }
    }

    public void DictionaryTest()
    {
        for (int i = 0; i < 10000; ++i)
        {
            mDictionaryList.Add(new Dictionary<int, int>());
        }
    }
}

運行在windows10 .net framework 4.6.1環境下

測試結果:生成1萬個List的時間爲1314Tick(0.1毫秒多點),內存佔用爲2140236字節(2.04MB多一點)。生成1萬個Dictionary的時間爲2087Tick(0.2毫秒多點),內存佔用爲2402276字節(2.29MB多一點)

結論:Dictionary的生成時間要長一點,Dictionary的內存佔用略大。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章