[實驗室] 實驗1. AutoMapper 5 真的變快了嗎 ??
實驗起源
最近AutoMapper 5 說改善效能問題,但是跟4比起來快多少或是新舊寫法有效能上的差異嗎?
先測試AutoMapper 4.2.1
程式碼如下
public ActionResult Index()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserViewModel>();
});
var mapper = config.CreateMapper();
User sam = new User()
{
UserID = 1,
Name = "sam"
};
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
UserViewModel model = mapper.Map<UserViewModel>(sam);
}
watch.Stop();
ViewBag.Milliseconds = watch.ElapsedMilliseconds;
return View();
}
測試五次
數據是2147,2132,2142,2149,2157
測試AutoMapper 5.1.1
先更新到最新版
一樣的程式碼再測試5次
數據是187,189,216,201,217
相信很多人想要4升級5 最小幅度修改的方法就是繼續用靜態Initialize
程式碼如下
public ActionResult Index()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<User, UserViewModel>();
});
User sam = new User()
{
UserID = 1,
Name = "sam"
};
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
UserViewModel model = Mapper.Map<UserViewModel>(sam);
}
watch.Stop();
ViewBag.Milliseconds = watch.ElapsedMilliseconds;
return View();
}
測試5次
數據是198,217,189,210,226
真的快好厲害
AutoMapper 5,真的比4快多了
舊專案快點升級到5吧 可以沿用靜態Initialize 的
程式碼一樣放到github
https://github.com/initialsam/AutoMapper5Demo
推薦連結
AutoMapper 5.0 speed increases (比較速度)
Removing the static API from AutoMapper (5有移除常用的Mapper.CreateMap)
補充測試
用原生的方式速度會有多快
public ActionResult Index()
{
User sam = new User()
{
UserID = 1,
Name = "sam"
};
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
UserViewModel model = new UserViewModel()
{
UserID = sam.UserID,
Name = sam.Name
};
}
watch.Stop();
ViewBag.Milliseconds = watch.ElapsedMilliseconds;
return View();
}
測試結果是25 ~ 50
原生比較快,但是整體開發上的流暢度 我還是會用AutoMapper 5來幫我處理
如果內容有誤請多鞭策謝謝