Linq to SQL的Select性能测试2011-08-07 博客园 紫色阴影前几天看到neuhawk 的文章linq to sql 的动态条件查询方法,文章最后选取了Ricom关于Linq to SQL的性能分析,里面说道Linq to SQL性能不错,有时候比ADO.NET还要好,当时觉得这分析结果难以让 人相信,应该Linq to SQL底层还是用ADO.NET 2.0实现的,即使效率再高也应该不能超越。加上最近几天 在MSDN论坛上看到有些人质疑Linq to SQL的效率,所以我做了一个很简单的测试,测试Linq to SQL的 select性能。以Northwind数据库为例,对Product表进行查询(我增加了里面的数据,增加到3000条),只选取 ProductID和ProductName,进行3000次查询,每次查询一条记录。首先看看使用SqlDataReader的代码: Stopwatch watch = new Stopwatch(); watch.Start();
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True")) { if (conn.State != System.Data.ConnectionState.Open) conn.Open(); for (int i = 1; i <= 3000; i++) { SqlCommand cmd = new SqlCommand( "SELECT ProductID,ProductName FROM Products WHERE ProductID=" + i.ToString(), conn); cmd.CommandType = System.Data.CommandType.Text; using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { Product p = new Product(); p.ProductID = (int)reader["ProductID"]; p.ProductName = (string)reader["ProductName"]; } }
} }
watch.Stop(); Console.WriteLine("[Using SqlReader] total time: " + watch.Elapsed.ToString ()); 这里的Product是用Linq to SQL Designer自动生成的,只有ProductID和ProductName属性。运行 的结果如下:[Using SqlReader] total time: 00:00:00.6521155