6

可能重复:
是否应该避免使用 LINQ,因为它很慢?

我喜欢 LINQ。正如我今天在另一篇文章中读到的“这是自切片面包以来最好的事情”,我完全同意。但是在我工作的公司里,其他人似乎都讨厌 LINQ。

几周前,我第一次使用 ReSharper,在编写代码时,ReSharper 突然告诉我,我的 foreach 循环可以转换为 LINQ 表达式。这对我来说就像魔术一样,我向我的同事展示了。令我惊讶的是,他说:“我希望它可以反过来工作并将 LINQ 变成循环。这样会快很多!”

那么LINQ-to-Objects真的那么慢吗?我自己试了一下。当我运行以下示例几次时,我得到大约 350 的 Elapsed Ticks。

        Stopwatch sw = new Stopwatch();

        List<Person> personList = new List<Person>();
        for (int i = 0; i < 5000; i++)
        {
            Person p = new Person() {ID = i};
            personList.Add(p);
        }

        sw.Start();

        Person searchPerson = null;

        foreach (Person person in personList)
        {
            if (person.ID == 4321)
            {
                searchPerson = person;
                break;
            }
        }

        sw.Stop();

        Console.WriteLine(sw.ElapsedTicks);

如果我将循环更改为 LINQ 查询(Resharper 将为我执行此操作),我会得到大约 900 的 ElapsedTicks。是循环的两倍多。

Person searchPerson = personList.FirstOrDefault(person => person.ID == 4321);

看起来 LINQ 确实更慢,如果你经常使用它,这可能是个问题。在我们公司,我们拥有大量数据。那么,避免 LINQ 是正确的决定还是我们做错了什么?

4

1 回答 1

16

Yes, it's slower. However, a portion of that delay is a one-time initialisation delay, rather than a per-iteration delay. The percentage difference is quite a bit lower on a 100k iteration loop.

The point to take away is that developer time is significantly more expensive than a small performance loss in your code, unless the customer is calling you up to complain about performance problems. Writing readable and maintainable code is much more important than micro-optimising your code.

As Eric Lippert pointed out so perfectly, LINQ should only be avoided if it's not fast enough.

于 2012-07-02T15:19:35.857 回答