Entity Framework天然是會比ADO.NET性能慢點,這個很少說了。直接上結果。數據庫
本該用測試項目的,不過我建了個aspx。下面是隨便測20遍獲得的結果性能
補充!!把12行改爲 list = db.Role.AsNoTracking().ToList();
因爲這隻作查詢,不須要上下文進行跟蹤。效率瞬間提高平均3-5倍,超越SqlDataAdapter,(其實不少人用SqlDataAdapter而不是用SqlCommand)
測試
測試代碼(建aspx,nuget拿EF6.1dll,建數據庫建表Role,本身插入6萬條數據,有主鍵自增)ui
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很利於開發進度。spa