[ASP.NET] Dictionary 和 Hashtable 区别

时间:2023-03-10 04:48:29
[ASP.NET] Dictionary 和 Hashtable 区别

Dictionary和Hashtable 是两个比较常用的表示键/值的集合,两者在实际使用过程中有何区别呢?

具体区别如下:

1. Hashtable不支持泛型,而Dictionary支持泛型。

2. Hashtable中的元素值为Object类型,所以在存储或检索值类型时通常会发生装箱和拆箱的操作,非常耗时。

3. 单线程中推荐使用Dictionary,有泛型优势。多线程中推荐使用Hashtable,默认的Hashtable允许单线程写入,多线程读取,对Hashtable进一步调用Synchronized()方法可以获得完全线程安全的类型,而Dictionary非线程安全,必须人为使用lock语句进行保护,效率大减。

4. 在通过代码测试的时候发现key是整数型Dictionary的效率比Hashtable快,如果key是字符串型,Dictionary的效率没有Hashtable快。

 /// <summary>
/// key为整型,Dictionary和Hashtable效率比较
/// </summary>
static void IntMethod()
{
Console.WriteLine("Key为整型,Dictionary和Hashtable查询性能比较:"); int count = ;
Dictionary<int, int> dictionary = new Dictionary<int, int>();
Hashtable hashtable = new Hashtable(); for (int i = ; i < count; i++)
{
dictionary.Add(i, i);
hashtable.Add(i, i);
} Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = ; i < count; i++)
{
int value = dictionary[i];
}
stopwatch.Stop();
Console.WriteLine("Dictionary:" + stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew();
for (int i = ; i < count; i++)
{
object value = hashtable[i];
}
stopwatch.Stop();
Console.WriteLine("Hashtable:" + stopwatch.ElapsedMilliseconds);
}
/// <summary>
/// Key为字符型,Dictionary和Hashtable查询性能比较
/// </summary>
static void StringMethod()
{
Console.WriteLine("Key为字符型,Dictionary和Hashtable查询性能比较:"); int count = ;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Hashtable hashtable = new Hashtable(); for (int i = ; i < count; i++)
{
dictionary.Add(i.ToString(), "String");
hashtable.Add(i, i);
} Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = ; i < count; i++)
{
string value = dictionary[i.ToString()];
}
stopwatch.Stop();
Console.WriteLine("Dictionary:" + stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew();
for (int i = ; i < count; i++)
{
object value = hashtable[i.ToString()];
}
stopwatch.Stop();
Console.WriteLine("Hashtable:" + stopwatch.ElapsedMilliseconds);
}

结果如下:

[ASP.NET] Dictionary 和 Hashtable 区别

参考:

http://www.cnblogs.com/akwwl/p/3680376.html