43

任何人都知道列表中 Where 和 FindAll 之间的任何速度差异。我知道 Where 是 IEnumerable 的一部分,而 FindAll 是 List 的一部分,我只是好奇什么更快。

4

5 回答 5

60

List<T> 类的 FindAll 方法实际上构造了一个新的列表对象,并将结果添加到其中。IEnumerable<T> 的 Where 扩展方法将简单地遍历现有列表并生成匹配结果的枚举,而无需创建或添加任何内容(除了枚举器本身)。

给定一个小集合,两者的表现可能相当。但是,给定一个更大的集合,Where 应该优于 FindAll,因为为包含结果而创建的新 List 必须动态增长以包含其他结果。随着匹配结果数量的增加,FindAll 的内存使用量也将开始呈指数增长,而 Where 应该具有恒定的最小内存使用量(本身......不包括你对结果所做的任何事情。)

于 2010-02-14T05:31:31.653 回答
11

FindAll 显然比 Where 慢,因为它需要创建一个新列表。

无论如何,我认为你真的应该考虑 Jon Hanna 的评论——你可能需要对你的结果做一些操作,并且 list 在很多情况下会比 IEnumerable 更有用。

我写了一个小测试,把它粘贴到 Console App 项目中。它测量时间/滴答声:函数执行、对结果集合的操作(以获得“真实”使用的性能,并确保编译器不会优化未使用的数据等。 - 我是 C# 新手,不会知道它是如何工作的,对不起)。

注意:除 WhereIENumerable() 之外的每个测量函数都会创建新的元素列表。我可能做错了什么,但显然迭代 IEnumerable 比迭代列表花费更多的时间。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Tests
{

    public class Dummy
    {
        public int Val;
        public Dummy(int val)
        {
            Val = val;
        }
    }
    public class WhereOrFindAll
    {
        const int ElCount = 20000000;
        const int FilterVal =1000;
        const int MaxVal = 2000;
        const bool CheckSum = true; // Checks sum of elements in list of resutls
        static List<Dummy> list = new List<Dummy>();
        public delegate void FuncToTest();

        public static long TestTicks(FuncToTest function, string msg)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            function();
            watch.Stop();
            Console.Write("\r\n"+msg + "\t ticks: " + (watch.ElapsedTicks));
            return watch.ElapsedTicks;
        }
        static void Check(List<Dummy> list)
        {
            if (!CheckSum) return;
            Stopwatch watch = new Stopwatch();
            watch.Start();

            long res=0;
            int count = list.Count;
            for (int i = 0; i < count; i++)     res += list[i].Val;
            for (int i = 0; i < count; i++)     res -= (long)(list[i].Val * 0.3);

            watch.Stop();
            Console.Write("\r\n\nCheck sum: " + res.ToString() + "\t iteration ticks: " + watch.ElapsedTicks);
        }
        static void Check(IEnumerable<Dummy> ieNumerable)
        {
            if (!CheckSum) return;
            Stopwatch watch = new Stopwatch();
            watch.Start();

            IEnumerator<Dummy> ieNumerator = ieNumerable.GetEnumerator();
            long res = 0;
            while (ieNumerator.MoveNext())  res += ieNumerator.Current.Val;
            ieNumerator=ieNumerable.GetEnumerator();
            while (ieNumerator.MoveNext())  res -= (long)(ieNumerator.Current.Val * 0.3);

            watch.Stop();
            Console.Write("\r\n\nCheck sum: " + res.ToString() + "\t iteration ticks :" + watch.ElapsedTicks);
        }
        static void Generate()
        {
            if (list.Count > 0)
                return;
            var rand = new Random();
            for (int i = 0; i < ElCount; i++)
                list.Add(new Dummy(rand.Next(MaxVal)));

        }
        static void For()
        {
            List<Dummy> resList = new List<Dummy>();
            int count = list.Count;
            for (int i = 0; i < count; i++)
            {
                if (list[i].Val < FilterVal)
                    resList.Add(list[i]);
            }      
            Check(resList);
        }
        static void Foreach()
        {
            List<Dummy> resList = new List<Dummy>();
            int count = list.Count;
            foreach (Dummy dummy in list)
            {
                if (dummy.Val < FilterVal)
                    resList.Add(dummy);
            }
            Check(resList);
        }
        static void WhereToList()
        {
            List<Dummy> resList = list.Where(x => x.Val < FilterVal).ToList<Dummy>();
            Check(resList);
        }
        static void WhereIEnumerable()
        {
            Stopwatch watch = new Stopwatch();
            IEnumerable<Dummy> iEnumerable = list.Where(x => x.Val < FilterVal);
            Check(iEnumerable);
        }
        static void FindAll()
        {
            List<Dummy> resList = list.FindAll(x => x.Val < FilterVal);
            Check(resList);
        }
        public static void Run()
        {
            Generate();
            long[] ticks = { 0, 0, 0, 0, 0 };
            for (int i = 0; i < 10; i++)
            {
                ticks[0] += TestTicks(For, "For \t\t");
                ticks[1] += TestTicks(Foreach, "Foreach \t");
                ticks[2] += TestTicks(WhereToList, "Where to list \t");
                ticks[3] += TestTicks(WhereIEnumerable, "Where Ienum \t");
                ticks[4] += TestTicks(FindAll, "FindAll \t");
                Console.Write("\r\n---------------");
            }
            for (int i = 0; i < 5; i++)
                Console.Write("\r\n"+ticks[i].ToString());
        }
    
    }

    class Program
    {
        static void Main(string[] args)
        {
            WhereOrFindAll.Run();
            Console.Read();
        }
    }
}

结果(滴答声) - 启用校验和(对结果进行一些操作),模式:不调试释放(CTRL+F5):

 - 16,222,276 (for ->list)
 - 17,151,121 (foreach -> list)
 -  4,741,494 (where ->list)
 - 27,122,285 (where ->ienum)
 - 18,821,571 (findall ->list)

CheckSum 已禁用(根本不使用返回的列表):

 - 10,885,004 (for ->list)
 - 11,221,888 (foreach ->list)
 - 18,688,433 (where ->list)
 -      1,075 (where ->ienum)
 - 13,720,243 (findall ->list)

您的结果可能会略有不同,要获得真正的结果,您需要更多的迭代。

于 2011-06-23T11:35:33.283 回答
4

更新(来自评论):查看我同意的代码,.Where 应该有,在最坏的情况下,相同的性能,但几乎总是更好。

原始答案:
.FindAll()应该更快,它利用已经知道 List 的大小并通过简单for循环遍历内部数组的优势。 .Where()必须启动一个枚举器(WhereIterator在这种情况下称为一个密封的框架类)并以不太具体的方式完成相同的工作。

但请记住, .Where() 是可枚举的,而不是主动在内存中创建 List 并填充它。它更像是一个流,因此非常大的东西的内存使用可能会有很大的不同。此外,您可以在 4.0 中使用 .Where() 方法更快地以并行方式开始使用结果。

于 2010-02-14T05:32:33.403 回答
2

Where比 .快得多FindAll。无论列表有多大,Where都需要完全相同的时间。

当然Where只是创建一个查询。它实际上并没有做任何事情,不像FindAll它创建一个列表。

于 2010-02-14T05:34:49.790 回答
-4

jrista 的回答是有道理的。但是,新列表添加了相同的对象,因此只是参考现有对象增长,这不应该那么慢。只要 3.5/Linq 扩展是可能的,Where 还是会更好。FindAll 在受限于 2.0 时更有意义

于 2010-07-15T12:31:41.690 回答