快速:查询语法与循环 [英] Which is fast : Query Syntax vs. Loops

查看:100
本文介绍了快速:查询语法与循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码提供了两种生成整数对的方法,它们的总和小于100,并且根据它们与(0,0)的距离以降序排列.

The following code provides two approaches that generate pairs of integers whose sum is less than 100, and they're arranged in descending order based on their distance from (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的第8本书 Effective C#.在整篇文章中,作者更加关注代码的语法,紧凑性和可读性,但是对性能几乎没有关注,几乎没有讨论.

This code is taken from the book Effective C# by Bill Wagner, Item 8. In the entire article, the author has focused more on the syntax, the compactness and the readability of the code, but paid very little attention to the performance, and almost didn't discuss it.

所以我基本上想知道哪种方法更快?通常,在性能上通常最好的是什么:查询语法或手动循环?

So I basically want to know, which approach is faster? And what is usually better at performance (in general) : Query Syntax or Manual Loops?

请详细讨论它们,并提供参考. :-)

Please discuss them in detail, providing references if any. :-)

推荐答案

分析是事实,但我的直觉是循环可能会更快.重要的是,在100%的性能方案中,性能差异中的99倍无关紧要.使用更具可读性的版本,当您以后需要维护它时,将来的自己会感谢您.

Profiling is truth, but my gut feeling would be that the loops are probably faster. The important thing is that 99 times out of 100 the performance difference just doesn't matter in the grand scheme of things. Use the more readable version and your future self will thank you when you need to maintain it later.

这篇关于快速:查询语法与循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆