什么是更快更方便:Hashtable或Dictionary <int,double>()?

ska*_*eff 1 .net c# memory-management data-structures

序言:我正在研究生产大型数据阵列的重载应用程序.

我写了下面的课

    using System;
    using System.Collections;
    using System.Collections.Generic;

    namespace CSharpSampleApplication.Data.CoreObjects
    {
        [Serializable]
        public class CalcItem
        {
            public CalcItem()
            {
                _additional = new Hashtable();
            }

            private readonly Hashtable _additional;

            public bool ContainsKey(int id)
            {
                return _additional.ContainsKey(id);
            }

            public void Add(int id, double value)
            {
                _additional.Add(id, value);
            }

            public DateTime Date { get; set; }

            public object this[int id]
            {
                get
                {
                    return _additional[id];
                }
            }
        }


    }
Run Code Online (Sandbox Code Playgroud)

然后,在另一个班级,我做了一个包含以下内容的经理:

    public List<CalcItem> CalcItems{ get; private set;}
    private readonly Dictionary<string, int> _keys;
    private int _index;
    private readonly object  _lock = new object();

    public int GetIndex(string key)
    {
        lock (_lock)
        {
            if (_keys.ContainsKey(key))
                return _keys[key];
            else
            {
                _index++;
                _keys.Add(key, _index);
                return _index;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

通过使用这些类,我记录了一些实时数据,例如:

                var clc = new CalcItem();
                clc.Date = DateTime.Now;
                clc.Add(_calcItemManager.GetIndex("testData"), r.Next() / 100.00);
                clc.Add(_calcItemManager.GetIndex("testData1"), r.Next() / 100.00);

                i++;

                if (i % 25 == 0)
                {
                    clc.Add(_calcItemManager.GetIndex("testData2"), r.Next()/100.00);
                    clc.Add(_calcItemManager.GetIndex("testData3"), r.Next()/100.00);
                    clc.Add(_calcItemManager.GetIndex("testData4"), r.Next()/100.00);
                    clc.Add(_calcItemManager.GetIndex("testData5"), r.Next()/100.00);
                }
                _calcItemManager.Add(clc);
Run Code Online (Sandbox Code Playgroud)

因此管理器为所有calcItems存储[string key] - [int index]绑定.

问题是:使用Dictionary<int, double>Hashtable()来优化内存使用和更快的性能是否更好?列表项 - 包含约1.000.000条记录CalcItem.Additional - 包含大约5-10条记录

Mar*_*ell 5

回答"更快"的愚蠢方法是为您的典型数据计时.然而,字典更方便(不需要演员)和高效(没有拳击).

但是,如果数据键是连续的,最好只使用List-of-double,并使用键作为索引(如果数据不是从0开始,则使用偏移量).