Insert測試,只測試1000條的情況,多了在實際的項目中應該就要另行處理了。 using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using S ...
Insert測試,只測試1000條的情況,多了在實際的項目中應該就要另行處理了。
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Diagnostics; using System.Linq; using EE.Service.DbAccess; using EE.Service.DbEntity; using EntityFramework.Extensions; using EntityFramework.Future; using MySql.Data.MySqlClient; namespace EE.Services.ConsoleTest.DbAccessTests { public class EFPerformanceTest { public static void Run() { //InsertTest(); UpdateTests(); } #region UpdateTest() static void UpdateTests() { var list = new List<SmsLog>(); for (int i = 0; i < 1000; i++) { list.Add(new SmsLog() { Id = i, AppId = $"{i}_", CreateTime = DateTime.Now }); } var sw = new Stopwatch(); Watcher(sw, EFInit, list.GetRange(0, 10)); Watcher(sw, MySqlSelect, list); Watcher(sw, EFSelect,list); Watcher(sw, MySqlUpdate, list); Watcher(sw, EFBulkUpdate, AddRangeId(list)); Watcher(sw, EFUpdateWithNoState, AddRangeId(list)); Watcher(sw, EFUpdate, AddRangeId(list)); } static IEnumerable<SmsLog> AddRangeId(IEnumerable<SmsLog> logs) { foreach (var log in logs) { log.Id += 1000; } return logs; } static int EFSelect(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { var val = 0; foreach (var item in items) { var rst = (from tb in db.SmsLogs where tb.Id == 1 select tb).FirstOrDefault(); if (rst != null) val++; } return val; } } static int EFUpdate(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { foreach (var item in items) { //db.SmsLogs.Attach(item); var o = db.SmsLogs.Where(x => x.Id == item.Id).FirstOrDefault(); if (o == null) continue; o.AppId = item.AppId+"U"; o.CreateTime = item.CreateTime; } var val = db.SaveChanges(); return val; } } static int EFUpdateWithNoState(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.ValidateOnSaveEnabled = false; db.Configuration.LazyLoadingEnabled = false; db.Configuration.ProxyCreationEnabled = false; var val = 0; foreach (var item in items) { //傳統更新方式 .. 更新不了(沒有狀態,無法完成更新) var o = db.SmsLogs.Where(x => x.Id == item.Id).FirstOrDefault(); if (o == null) continue; o.AppId = item.AppId+"SU"; o.CreateTime = item.CreateTime; } val = db.SaveChanges(); return val; } } static int EFBulkUpdate(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { foreach (var item in items) { var o = db.SmsLogs.Where(x => x.Id == item.Id).FirstOrDefault(); if (o == null) continue; o.AppId = item.AppId+"BU"; o.CreateTime = item.CreateTime; } db.BulkSaveChanges(); return 0; } } static int MySqlUpdate(IEnumerable<SmsLog> items) { var val = 0; var connStr = ConfigurationManager.ConnectionStrings["EEServiceLogDb"].ConnectionString; using (var conn = new MySqlConnection(connStr)) { conn.Open(); foreach (var item in items) { val += MySqlHelper.ExecuteNonQuery(conn, "Update SmsLogs set AppId=@appId,CreateTime=@createTime where Id = @id;", new MySqlParameter("@appId", item.AppId+"S"), new MySqlParameter("@createTime", item.CreateTime), new MySqlParameter("@id", item.Id)); } conn.Close(); } return val; } static int MySqlSelect(IEnumerable<SmsLog> items) { var val = 0; var connStr = ConfigurationManager.ConnectionStrings["EEServiceLogDb"].ConnectionString; using (var conn = new MySqlConnection(connStr)) { conn.Open(); foreach (var item in items) { var dr = MySqlHelper.ExecuteReader(conn, "select * from SmsLogs where Id = @id;", new[] { new MySqlParameter("@id", item.Id) }); while (dr.Read()) { val += 1; } dr.Close(); } conn.Close(); } return val; } #endregion #region InsertTest() static void InsertTest() { var list = new List<SmsLog>(); for (int i = 0; i < 1000; i++) { list.Add(new SmsLog() { AppId = $"{i}", CreateTime = DateTime.Now }); } var sw = new Stopwatch(); Watcher(sw, EFInit, list.GetRange(0, 10)); Watcher(sw, EFBulkInsert, list); Watcher(sw, EFInsertWithNoState, list); Watcher(sw, EFInsert, list); Watcher(sw, MySqlInsert, list); //Watcher(sw, EFInsert, list); } static int EFInsert(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { foreach (var item in items) db.SmsLogs.Add(item); var val = db.SaveChanges(); return val; } } static int EFInsertWithNoState(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.ValidateOnSaveEnabled = false; db.Configuration.LazyLoadingEnabled = false; db.Configuration.ProxyCreationEnabled = false; foreach (var item in items) db.SmsLogs.Add(item); var val = db.SaveChanges(); return val; } } static int EFBulkInsert(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { //db.Configuration.AutoDetectChangesEnabled = false; //db.Configuration.ValidateOnSaveEnabled = false; foreach (var item in items) db.SmsLogs.Add(item); db.BulkSaveChanges(); return 0; } } static int MySqlInsert(IEnumerable<SmsLog> items) { var val = 0; var connStr = ConfigurationManager.ConnectionStrings["EEServiceLogDb"].ConnectionString; using (var conn = new MySqlConnection(connStr)) { conn.Open(); foreach (var item in items) { val += MySqlHelper.ExecuteNonQuery(conn, "Insert into SmsLogs(AppId,CreateTime)values(@appId,@createTime)", new MySqlParameter("@appId", item.AppId), new MySqlParameter("@createTime", item.CreateTime)); } conn.Close(); } return val; } #endregion /// <summary> /// 初始化一下,儘量減少EF初始化時間的影響 /// </summary> /// <param name="items"></param> /// <returns></returns> static int EFInit(IEnumerable<SmsLog> items) { using (var db = new ServiceLogDbContent()) { foreach (var item in items) { var o = db.SmsLogs.FirstOrDefault(x => x.Id == item.Id); if (o != null) { o.AppId = "Init"; } } var val = db.SaveChanges(); return val; } } static void Watcher<T>(Stopwatch stopwatch, Func<IEnumerable<T>, int> func, IEnumerable<T> list) { if (stopwatch == null) stopwatch = new Stopwatch(); stopwatch.Reset(); Console.WriteLine($"[{DateTime.Now:HH:mm:ss ffffff}] {func.Method.Name} BEGIN ====================================================="); stopwatch.Start(); var val = func(list); stopwatch.Stop(); Console.WriteLine($"[{DateTime.Now:HH:mm:ss ffffff}] {func.Method.Name}[{stopwatch.Elapsed} IN<{list.Count()}> -> RS<{val}>]"); //Console.WriteLine($"[{DateTime.Now:HH:mm:ss ffffff}] {func.Method.Name} end"); } } }View Code
本機開發機,DB在內網伺服器上。測試結果:
可以看到,EF的初始執行還是蠻耗時間的。擴展的BuilInsert要比迴圈的MySqlInsert語句效率還好一些。關掉狀態跟蹤與預設情況,差別不大(不知是不是我寫的有問題)。
這麼一看,是因為查詢慢嗎?
更新的方式就是選Where出對象,再修改對象的值,再SaveChagnes。 難道是我寫的方式不對?為什麼查詢這麼慢?
-----------------------------------------------------------------------------------------------------------------------------------
原來不是我的寫的問題,而是配置問題,連接串中沒有池化與有池化的結果相差近10倍。這算什麼???
Pooling=true;
連接串中的這個就是影響性能差別巨大的“元凶”