C# foreach,linq,delegate集合查询的性能比较

因为前面,叶鹏(http://www.cnblogs.com/jqbird/archive/2011/11/04/2235627.html 已经做过测试,我只是重新验证了一下,发现他的结果是不对的。我得出的结果是,foreach > delegate > linq,这个是我反复测试的结果

代码和他的差不多

        public class TestClass
        {
            public int Id
            {
                get;
                set;
            }
            public string Name
            {
                get;
                set;
            }
        }

        static void Main(string[] args)
        {
            test();
        }

 

        private static void test()
        {
            IList<TestClass> list1 = new List<TestClass>();

            for (int i = 0; i < 10000000; i++)
            {
                TestClass tc = new TestClass();
                tc.Id = i;
                tc.Name = "Test Data" + i;
                list1.Add(tc);
            }

            Stopwatch timer = new Stopwatch();

            #region for circle
            timer.Start();
            int count = 0;
            foreach (TestClass tc in list1)
            {
                if (1 <= tc.Id && tc.Id < 1000)
                {
                    count++;
                }
            }
            timer.Stop();

            Console.Write("Count:" + count + ", for circle time:");
            Console.WriteLine(timer.Elapsed.Ticks);
            #endregion

            #region linq
            timer = new Stopwatch();
            timer.Start();
            int count2 = 0;
            count2 = list1.Where(p => p.Id >= 1 && p.Id < 1000).Count();
            timer.Stop();

            Console.Write("Count:" + count2 + ", linq time:");
            Console.WriteLine(timer.Elapsed.Ticks);
            #endregion

            #region delegate
            timer = new Stopwatch();
            timer.Start();
            int count3 = list1.ToList().FindAll(delegate(TestClass post)
            {
                return post.Id >= 1 && post.Id < 1000;
            }).Count;

            timer.Stop();
            Console.Write("Count:" + count3 + ", delegate time:");
            Console.WriteLine(timer.Elapsed.Ticks);
            #endregion

            Console.Read();
        }

而我得出的结论:

 

希望广大朋友指正,水平有限!!

 

转载于:https://www.cnblogs.com/zbphot/archive/2011/11/04/2235832.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值