for/foreach/linq执行效率测试

测试代码
        private static void Test1(int count)
        {
            int s;
            List<int> list = new List<int>();
            for (int i = 0; i < 10000; i++)
            {
                list.Add(i);
            }
            Console.WriteLine("这是测试for/linq/foreach效率开始");
            DateTime d1 = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                var roleQuery = from r in list
                                where r == 3500
                                select r;
                foreach (var role in roleQuery)
                {
                    s = role;
                }
                Console.WriteLine("测试Linq第" + i +"次");
            }
            DateTime d2 = DateTime.Now;
            DateTime d3 = DateTime.Now;
            for (int c = 0; c < count; c++)
            {
                foreach (int role in list)
                {
                    if (role == 350)
                    {
                        s = role;
                    }
                }
                Console.WriteLine("测试foreach第" + c + "次");
            }
            DateTime d4 = DateTime.Now;
            DateTime d5 = DateTime.Now;
            for (int c = 0; c < count; c++)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] == 350)
                    {
                        s = list[i];
                    }
                }
                Console.WriteLine("测试for第" + c + "次");
            }
            DateTime d6 = DateTime.Now;
            DateTime d7 = DateTime.Now;
            for (int c = 0; c < count; c++)
            {
                int i=0;
                while ( i<list.Count)
                {
                    if (list[i] == 350)
                    {
                        s = list[i];
                    }
                    i++;
                }
                Console.WriteLine("测试while第" + c + "次");
            }
            DateTime d8 = DateTime.Now;
            Console.WriteLine("linq测试时长为:" + (d2 - d1).ToString());
            Console.WriteLine("foreach测试时长为:" + (d4 - d3).ToString());
            Console.WriteLine("for测试时长为:" + (d6 - d5).ToString());
            Console.WriteLine("while测试时长为:" + (d8 - d7).ToString());
            Console.Read();
        }
 
调用代码
        static void Main(string[] args)
        {
            //NewMethod();
            int count = 100000000;
            Test1(count / 1000); //太大了时间太长
            //Test2(count);
        }
 
执行结果




posted @ 2013-05-18 00:48  Adming  阅读(754)  评论(0编辑  收藏  举报