最近在学习Linq,我之前一直习惯使用DataTable和DataView的,尤其是一万条以上的记录,都要转成DataView,这样查找速度快。
至于Linq,我知道它肯定比DataView要慢的,但慢到什么程度,还没有测试过,现在就来一发:
1.测试条件
共生成10000条记录(姓名,成绩),其中成绩用(0-100)的随机整数模拟,再随机创建5000个随机整数,在之前的集合中查找,模拟实际的查询操作
DataView:
private void TestSpeed_Table()
{
DataTable dt = new DataTable();
dt.Columns.Add("userName", typeof(string));
dt.Columns.Add("score", typeof(int));
for(int i=0;i< testCount;i++)
{
dt.Rows.Add(new object[] { "name"+i, GenScore() });
}
DataView dv = new DataView(dt);
dv.Sort = "score";
int findCount = 0;
Stopwatch st = new Stopwatch();
st.Start();
for (int i=0;i<5000;i++)
{
int score = GenScore();
int pos = dv.Find(score);
if (pos >= 0)
findCount++;
}
st.Stop();
Console.WriteLine(st.ElapsedMilliseconds+":find count:"+findCount);
Console.ReadLine();//1毫秒
}
private void TestSpeed_Linq()
{
List<User> lst = new List<User>();
for(int i=0;i<testCount;i++)
{
lst.Add(new User
{
UserName = "name" + i,
Score = GenScore()
});
}
Stopwatch st = new Stopwatch();
st.Start();
int findCount = 0;
for (int i = 0; i < 5000; i++)
{
int score = GenScore();
var q=lst.First<User>(a =>a.Score==score);
if (q != null)
findCount++;
}
st.Stop();
Console.WriteLine(st.ElapsedMilliseconds + ":find count:" + findCount);
Console.ReadLine();//40毫秒
}
结果分别为1毫秒和40毫秒,相差40倍。查5000次是DataView的最小次数,小于这个次数所用时间都是0。
将查询降到1000次,Linq用的时间大概是3、4秒,这个数量级看来Linq还凑和。
DataView为什么快?因为它在配置了Sort后,相当于在内存表里建了索引,所以速度是相当的快。虽然是一个很老的技术,但仍然是我最爱用的。