Hashtable和Directory性能比较
Hashtable和Directory性能比较
在.net1.1里经常会使用到Hashtable,到里.net 2.0以后我发现有了一个很好用的IDirectory<TKey,TValue>实现类 Directory<TKey,TValue>。但还是会担心Directory<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是整数型Directory的效率比Hashtable快3到4倍,
如果key是字符串型,Directory的效率只有Hashtable的一半。
另外使用TryGetValue对效率没什么影响。
posted on 2013-04-27 11:26 peter.peng 阅读(770) 评论(1) 编辑 收藏 举报