以下代码提供了两种方法来生成总和小于 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);
}
这段代码摘自 Bill Wagner 的《Effective C# 》一书,第 8 条。在整篇文章中,作者更多地关注代码的语法、紧凑性和可读性,而很少关注性能,几乎没有讨论它。
所以我基本上想知道,哪种方法更快?什么通常在性能上更好(通常):查询语法或手动循环?
请详细讨论它们,如果有的话,请提供参考。:-)