写程序时经常会对键值进行查找,感觉Hashtable会比DataTable稍快,但到底快多少?在需要频繁查找DataTable的情况下是否有必要利用Hashtable做缓存?DataTable列数的多少是否会影响到查找效率?今天做了个测试与大家分享
static void 测试()
{
int count=1000000;
System.Collections.Hashtable ht=new System.Collections.Hashtable(7);
DataTable t1=new DataTable();
t1.Columns.Add("ID",typeof(int));
t1.Columns.Add("value",typeof(int));
t1.PrimaryKey=new DataColumn[] { t1.Columns["ID"] };
DataTable t2=new DataTable();
t2.Columns.Add("ID",typeof(int));
t2.Columns.Add("value",typeof(int));
t2.Columns.Add("string0",typeof(string));
t2.Columns.Add("string1",typeof(string));
t2.Columns.Add("string2",typeof(string));
t2.Columns.Add("string3",typeof(string));
t2.Columns.Add("string4",typeof(string));
t2.Columns.Add("string5",typeof(string));
t2.Columns.Add("string6",typeof(string));
t2.Columns.Add("string7",typeof(string));
t2.Columns.Add("string8",typeof(string));
t2.Columns.Add("string9",typeof(string));
t2.PrimaryKey=new DataColumn[] { t2.Columns["ID"] };
object[] test=new object[count];
for(int i=0;i<count;i++)
{
test[i]=Socg.Random.RandomInt(0,count-1);//利用GUID生成的随机数
ht.Add(i,i);
t1.Rows.Add(i,i);
t2.Rows.Add(i,i,"a","b","c","d","e","f","g","h","i","j");
}
Socg.Diagnostics.TimeHash time=new Socg.Diagnostics.TimeHash();//记录时间
time["HashTable"].Start();
for(int i=0;i<count;i++)
{
ht.ContainsKey(test[i]);
}
time["HashTable"].Stop();
time["DataTable"].Start();
for(int i=0;i<count;i++)
{
t1.Rows.Find(test[i]);
}
time["DataTable"].Stop();
time["DataTable多列"].Start();
for(int i=0;i<count;i++)
{
t2.Rows.Find(test[i]);
}
time["DataTable多列"].Stop();
MessageBox.Show(time.ToString());
}
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做缓存。