这次对比是用int 来比较的, Hashtable 比 Dictionary 慢的原因是: Hashtable.Add(Object key, Object value), 两个参数都需要进行装箱操作, 严重拖慢了速度; String 类型没有测试, 但是根据比较数据, string 作为 Object 会快很多.
MSDN解释: Dictionary 类与 Hashtable 类的功能相同。对于值类型,特定类型(不包括 Object)的 Dictionary 的性能优于 Hashtable,这是因为 Hashtable 的元素属于 Object 类型,所以在存储或检索值类型时通常发生装箱和取消装箱操作。
static void Main()
{
int MaxCount = 1000000;
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
Dictionary<int, int> dic = new Dictionary<int, int>(MaxCount);
stopwatch.Reset();
stopwatch.Start();
for(int i=0;i<MaxCount;i++)
dic.Add(i, i);
stopwatch.Stop();
Console.WriteLine("Dictionary创建" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds);
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < MaxCount; i++)
dic[i]++;
stopwatch.Stop();
Console.WriteLine("Dictionary修改" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds);
Hashtable ht = new Hashtable(MaxCount);
stopwatch.Reset();
stopwatch.Start();
for(int i=0;i<MaxCount;i++)
ht.Add(i, i); //Hashtable.Add(Object key, Object value), 前后两个i 都需要装箱, 所以执行了两次装箱
stopwatch.Stop();
Console.WriteLine("Hashtable 创建" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds + " ----装箱");
Object o = new Object();
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < MaxCount; i++)
ht[i]=i; //消耗318秒, 如果是ht[i]=o;就消耗165秒, 由此可见hashtable 主要慢在装箱上
stopwatch.Stop();
Console.WriteLine("Hashtable 修改" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds + " ----装箱");
Hashtable ht2 = new Hashtable(MaxCount);
Object[] arrayo = new Object[MaxCount];
for (int i = 0; i < MaxCount; i++)
arrayo[i] = i;
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < MaxCount; i++)
ht2.Add(arrayo[i], arrayo[i]);
stopwatch.Stop();
Console.WriteLine("Hashtable 创建" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds + " ----无装箱操作");
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < MaxCount; i++)
ht[arrayo[i]] = o;
stopwatch.Stop();
Console.WriteLine("Hashtable 修改" + MaxCount + "条记录消耗时间: " + stopwatch.Elapsed.TotalMilliseconds + " ----无装箱操作");
}
比较结果
Dictionary创建1000000条记录消耗时间: 16.6205
Dictionary修改1000000条记录消耗时间: 34.2627
Hashtable 创建1000000条记录消耗时间: 154.4049 ----装箱
Hashtable 修改1000000条记录消耗时间: 319.7699 ----装箱
Hashtable 创建1000000条记录消耗时间: 33.8827 ----无装箱操作
Hashtable 修改1000000条记录消耗时间: 42.2699 ----无装箱操作