代码改变世界

Linq与FindAll查找效率引发的思考

2012-12-19 23:02  Kevin Zhou  阅读(811)  评论(1编辑  收藏  举报
        public static void Main()
        {
            var list = new List<BaseData>();
            var rand = new Random();
            
            for (int i = 0; i < 10000000; i++)
            {
                list.Add(new BaseData { Keyword = "啦啦啦", KeywordType = rand.Next(1, 7) });
            }
            Console.WriteLine("construct list finished.");

            var filter = new int[] { 1, 2, 3, 4, 6, 7 };

            var stop = new Stopwatch();
            stop.Start();

            var query = from k in list
                        where k.KeywordType != 5
                        select k;

            stop.Stop();

            Console.WriteLine("linq ticks:" + stop.Elapsed.Ticks);
            Console.WriteLine("linq find result:" + query.Count());


            var stop2 = new Stopwatch();
            stop2.Start();
            
            var query2 = list.FindAll(_ => _.KeywordType != 5);
            
            stop2.Stop();

            Console.WriteLine("find all ticks:" + stop2.Elapsed.Ticks);
            Console.WriteLine("find all result:" + query2.Count);

            

            Console.ReadKey();
        }

结果是:

construct list finished.
linq ticks:1214
linq find result:8333767
find all ticks:7379030
find all result:8333767

今天在网上,Google了半天List的Find、FindAll机制,无果!晚上回来,写了一段小Demo;
发现Linq的性能更好;

Linq的查找机制比Find、FindAll好在哪里?