您的位置:首页 > 其它

Hashtable和Dictionary性能比较

2010-04-22 23:16 351 查看
在.net1.1里经常会使用到Hashtable,到里.net 2.0以后我发现有了一个很好用的IDictionary<TKey,TValue>实现类Dictionary<TKey,TValue>。但还是会担心Dictionary<TKey,TValue>的检索效率是否跟Hashtable相当,

据我了解ArrayList的检索效率是非常差的,BinarySearch也不如Hashtable.所以做了一个测试。

class Program
{
static void Main(string[] args)
{
IntTest();

StringTest();

IntTryGetValueTest();

Console.WriteLine("=========");

IntTest();

StringTest();

IntTryGetValueTest();

Console.ReadLine();
}

static void IntTest()
{
IDictionary<int, int> id = new Dictionary<int, int>();

Hashtable ht = new Hashtable();

int count = 1000000;

for (int i = 0; i < count; i++)
{
id.Add(i, i);

ht.Add(i, i);
}
//////////////
Stopwatch st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
int str = id[i];
}

st.Stop();

Console.WriteLine(string.Format("int类型,Directory:{0}", st.ElapsedMilliseconds));
//////////////
st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
object obj = ht[i];
}

st.Stop();

Console.WriteLine(string.Format("int类型,Hashtable:{0}", st.ElapsedMilliseconds));
}

static void StringTest()
{
IDictionary<string, string> id = new Dictionary<string, string>();

Hashtable ht = new Hashtable();

int count = 1000000;

for (int i = 0; i < count; i++)
{
string str = i.ToString();

id.Add(str, str);

ht.Add(str, str);
}
//////////////
Stopwatch st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
string i2 = id[i.ToString()];
}

st.Stop();

Console.WriteLine(string.Format("string类型,Directory:{0}", st.ElapsedMilliseconds));
//////////////
st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
object obj = ht[i.ToString()];
}

st.Stop();

Console.WriteLine(string.Format("string类型,Hashtable:{0}", st.ElapsedMilliseconds));

}

static void IntTryGetValueTest()
{
IDictionary<int, int> id = new Dictionary<int, int>();

Hashtable ht = new Hashtable();

int count = 1000000;

for (int i = 0; i < count; i++)
{
id.Add(i, i);

ht.Add(i, i);
}
//////////////
Stopwatch st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
int i2 = 0;

id.TryGetValue(i, out i2);

}

st.Stop();

Console.WriteLine(string.Format("IntTryGetValue,Directory:{0}", st.ElapsedMilliseconds));
//////////////
st = Stopwatch.StartNew();

for (int i = 0; i < count; i++)
{
object obj = ht[i];
}

st.Stop();

Console.WriteLine(string.Format("int类型,Hashtable:{0}", st.ElapsedMilliseconds));
}
}


输出为:

int类型,Directory:49

int类型,Hashtable:254

string类型,Directory:1112

string类型,Hashtable:511

IntTryGetValue,Directory:50

int类型,Hashtable:251

=========

int类型,Directory:48

int类型,Hashtable:201

string类型,Directory:944

string类型,Hashtable:505

IntTryGetValue,Directory:51

int类型,Hashtable:167

~~~~~~~~~~~~~~~~~~·

从结果我们可以发现如果key是整数型Dictionary的效率比Hashtable快3到4倍,

如果key是字符串型,Dictionary的效率只有Hashtable的一半。

另外使用TryGetValue对效率没什么影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: