一个Entity Framework、ADO.NET查询性能测试
Entity Framework自然是会比ADO.NET性能慢点,这个不多说了。直接上结果。
本该用测试项目的,不过我建了个aspx。下面是随便测20遍得到的结果
补充!!把12行改成 list = db.Role.AsNoTracking().ToList();
由于这只做查询,不需要上下文进行跟踪。效率瞬间提升平均3-5倍,超越SqlDataAdapter,(其实很多人用SqlDataAdapter而不是用SqlCommand)
测试代码(建aspx,nuget拿EF6.1dll,建数据库建表Role,自己插入6万条数据,有主键自增)
1 string connStr = "server=localhost;database=EF;uid=sa;pwd=your1234;Persist Security Info=True"; 2 3 4 List<Role> list = new List<Role>(); 5 DateTime start = DateTime.MinValue; 6 DateTime end = DateTime.MinValue; 7 8 Response.Write("查询6万条数据耗时测试 <br />"); 9 using (var db = new DBContext(connStr)) 10 { 11 start = DateTime.Now; 12 list = db.Role.ToList(); 13 end = DateTime.Now; 14 Response.Write("EF6.1,耗时:" + (end - start).ToString() + " <br />"); 15 } 16 17 18 start = DateTime.Now; 19 SqlConnection conn = new SqlConnection(connStr); 20 conn.Open(); 21 SqlCommand cmd = new SqlCommand("select * from [Role]", conn); 22 SqlDataReader dr = cmd.ExecuteReader(); 23 while (dr.Read()) 24 { 25 list.Add(new Role() 26 { 27 ID = dr.GetInt32(0), 28 Name = dr.GetString(1), 29 Desc = dr.GetString(2), 30 CreateDate = dr.GetDateTime(3), 31 ModifyDate = dr.GetDateTime(4) 32 }); 33 } 34 dr.Close(); 35 36 end = DateTime.Now; 37 Response.Write("ADO.NET SqlCommand + SqlDataReader,耗时:" + (end - start).ToString() + " <br />"); 38 39 start = DateTime.Now; 40 SqlDataAdapter sda = new SqlDataAdapter("select * from [Role]", conn); 41 var ds = new DataSet(); 42 sda.Fill(ds); 43 list = (from item in ds.Tables[0].AsEnumerable() 44 select new Role 45 { 46 ID = item.Field<int>("ID"), 47 Name = item.Field<string>("Name"), 48 Desc = item.Field<string>("Desc"), 49 CreateDate = item.Field<DateTime>("CreateDate"), 50 ModifyDate = item.Field<DateTime>("ModifyDate"), 51 52 }).ToList(); 53 54 conn.Close(); 55 56 end = DateTime.Now; 57 Response.Write("ADO.NET SqlDataAdapter + DataSet,耗时:" + (end - start).ToString() + " <br />");
EF其实是不错的东西,楼主很喜欢;很多人说EF性能差,不过我觉得EF很利于开发进度。