Fork me on GitHub

描述:项目中使用了linq,发现写的顺序不一样最后的结果也不一样,效率也不一样。

Linq的执行效率对比

List<int> source = new List<int>();
var rand = new Random();
int i = 5000;
while (i > 0)
{
    i--;
    source.Add(rand.Next(1, 500));
}

Stopwatch watch = new Stopwatch();

watch.Restart();
var temp2 = from s in source orderby s where s > 100 select s;
int count2 = temp2.Count();
watch.Stop();
Console.WriteLine("orderby s where s > 100: " + watch.ElapsedTicks);

watch.Restart();
var temp1 = from s in source where s > 100 orderby s select s;
int count = temp1.Count();
watch.Stop();
Console.WriteLine("where s > 100 orderby s: " + watch.ElapsedTicks);

效果如图:

效率相差还是蛮大的,差不多10倍,所以linq的执行要按照一定的顺序,不能随心所欲。

Linq优化

linq和sql的语法差不多,所以可以按照sql的执行顺序对linq进行优化,建议顺序

1.FROM
2.join
3.WHERE
4.GROUP BY

5.ORDER BY
6.SELECT

 linq详解

https://www.cnblogs.com/zhao123/p/5621841.html

posted on 2018-09-21 22:54  lingfeng95  阅读(2358)  评论(1编辑  收藏  举报