Naw*_*waz 4 c# performance loops code-readability linq-query-syntax
下面的代码提供了两种方法,它们生成总和小于100的整数对,并且它们根据它们与(0,0)的距离按降序排列.
//approach 1
private static IEnumerable<Tuple<int,int>> ProduceIndices3()
{
var storage = new List<Tuple<int, int>>();
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
if (x + y < 100)
storage.Add(Tuple.Create(x, y));
}
}
storage.Sort((p1,p2) =>
(p2.Item1 * p2.Item1 +
p2.Item2 * p2.Item2).CompareTo(
p1.Item1 * p1.Item1 +
p1.Item2 * p1.Item2));
return storage;
}
//approach 2
private static IEnumerable<Tuple<int, int>> QueryIndices3()
{
return from x in Enumerable.Range(0, 100)
from y in Enumerable.Range(0, 100)
where x + y < 100
orderby (x * x + y * y) descending
select Tuple.Create(x, y);
}
Run Code Online (Sandbox Code Playgroud)
这段代码来自Bill Wagner,第8章的Effective C#一书.在整篇文章中,作者更多地关注代码的语法,紧凑性和可读性,但很少关注性能,几乎没有讨论它.
所以我基本上想知道,哪种方法更快?性能通常更好(通常):查询语法或手动循环?
请详细讨论,如有的话,提供参考.:-)