linq语句复杂查询和分开查询的性能对比

刚开始以为复杂的linq语句查询会不会比分开来写效率高,因为复杂的语句关联和嵌套多,执行应该慢。分开写虽然多了一次io处理,但是关联比较少,数据了比价少,和朋友讨了一下,回家就做了个测试,废话不多说,直接上代码。

  var dbconten2 = new SqlSugarTestEntities();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
var orderproduct = (from o in dbconten2.order
join p in dbconten2.product on o.sku equals p.sku
select new
{
sku=o.sku,
name=o.name
}).ToList();
var lable = (from m in dbconten2.labelMbp
join l in dbconten2.lable on m.lableID equals l.id
select new
{
sku=m.sku,
img=l.imgUrl
}).ToList();
sw2.Stop();
var results = (from a in orderproduct
join b in lable on a.sku equals b.sku into h
from n in h.DefaultIfEmpty()
select new
{
sku = a.sku,
img =n==null?"": n.img,
name = a.name
}).ToList(); var time2 = sw2.ElapsedMilliseconds.ToString(); var dbconten = new SqlSugarTestEntities();
Stopwatch sw = new Stopwatch();
sw.Start();
var result = (from o in dbconten.order
join p in dbconten.product on o.sku equals p.sku
join m in dbconten.labelMbp on p.sku equals m.sku into mbp
from mp in mbp.DefaultIfEmpty()
join l in dbconten.lable on mp.lableID equals l.id into ld
from d in ld.DefaultIfEmpty()
select new
{
sku = p.sku,
img = d.imgUrl,
name = o.name });
var ss = result.ToList();
var aa= ss.GroupBy(g => g.sku).ToList(); sw.Stop();
var time = sw.ElapsedMilliseconds.ToString();
Console.WriteLine("linq:" + time);
//Console.WriteLine("分开:" + time2);

数据库io操作耗时还是比价大的,在操作数据库时能一次查询出来就不用多次。

性能永远是个值得讨论的话题,直接自己真正的测试了才知道结果,就像好多人争论的 in,not in 一样,花大把的时间争论,还不如自己花点时间测试

事实胜于雄辩,所有的讨论都没有直接测试来的直接。

上一篇:Android悬浮窗及其拖动事件


下一篇:【Beta阶段】第三次Scrum Meeting!