Hashtable VS DataTable

写程序时经常会对键值进行查找,感觉Hashtable会比DataTable稍快,但到底快多少?在需要频繁查找DataTable的情况下是否有必要利用Hashtable做缓存?DataTable列数的多少是否会影响到查找效率?今天做了个测试与大家分享
[csharp]  view plain copy
  1. static void 测试()  
  2. {  
  3.     int count=1000000;  
  4.     System.Collections.Hashtable ht=new System.Collections.Hashtable(7);  
  5.     DataTable t1=new DataTable();  
  6.     t1.Columns.Add("ID",typeof(int));  
  7.     t1.Columns.Add("value",typeof(int));  
  8.     t1.PrimaryKey=new DataColumn[] { t1.Columns["ID"] };  
  9.     DataTable t2=new DataTable();  
  10.     t2.Columns.Add("ID",typeof(int));  
  11.     t2.Columns.Add("value",typeof(int));  
  12.     t2.Columns.Add("string0",typeof(string));  
  13.     t2.Columns.Add("string1",typeof(string));  
  14.     t2.Columns.Add("string2",typeof(string));  
  15.     t2.Columns.Add("string3",typeof(string));  
  16.     t2.Columns.Add("string4",typeof(string));  
  17.     t2.Columns.Add("string5",typeof(string));  
  18.     t2.Columns.Add("string6",typeof(string));  
  19.     t2.Columns.Add("string7",typeof(string));  
  20.     t2.Columns.Add("string8",typeof(string));  
  21.     t2.Columns.Add("string9",typeof(string));  
  22.     t2.PrimaryKey=new DataColumn[] { t2.Columns["ID"] };  
  23.     object[] test=new object[count];  
  24.     for(int i=0;i<count;i++)  
  25.     {  
  26.         test[i]=Socg.Random.RandomInt(0,count-1);//利用GUID生成的随机数  
  27.            ht.Add(i,i);  
  28.         t1.Rows.Add(i,i);  
  29.         t2.Rows.Add(i,i,"a","b","c","d","e","f","g","h","i","j");  
  30.     }  
  31.   
  32.     Socg.Diagnostics.TimeHash time=new Socg.Diagnostics.TimeHash();//记录时间  
  33.   
  34.       time["HashTable"].Start();  
  35.     for(int i=0;i<count;i++)  
  36.     {  
  37.         ht.ContainsKey(test[i]);  
  38.     }  
  39.     time["HashTable"].Stop();  
  40.   
  41.     time["DataTable"].Start();  
  42.     for(int i=0;i<count;i++)  
  43.     {  
  44.         t1.Rows.Find(test[i]);  
  45.     }  
  46.     time["DataTable"].Stop();  
  47.   
  48.     time["DataTable多列"].Start();  
  49.     for(int i=0;i<count;i++)  
  50.     {  
  51.         t2.Rows.Find(test[i]);  
  52.     }  
  53.     time["DataTable多列"].Stop();  
  54.   
  55.     MessageBox.Show(time.ToString());  
  56. }  


 3次测试结果
HashTable:       0.359,0.344,0.344
DataTable:        3.656,3.516,3.500
DataTable多列:3.609,3.516,3.516

后将主键定义成string也做了测试
HashTable:       0.484,0.469,0.469
DataTable:        9.406,9.516,9.375
DataTable多列:8.766,9.016,8.875


HashTable比想象中的要快,DataTable的列数不会影响到查找效率,但数据类型对DataTable的查找性能影响较大,在频繁查找DataTable时还是应该考虑用HashTable做缓存

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值