for/foreach/linq效率测试

for/foreach/linq效率测试
int count = 0;
            Random r = new Random();
            List<byte> list = new List<byte>();
            Console.WriteLine("开始for循环添加:");
            int ticks = Environment.TickCount;

            for (int i = 0; i < 10000000; i++)
            {
                list.Add((byte)r.Next(-1, 255));
            }
            int temp = Math.Abs(Environment.TickCount - ticks);
            Console.WriteLine("经过的时间为:"+temp);

            Console.WriteLine("开始foreach查询:");
            ticks = Environment.TickCount;
            count = 0;
            foreach (byte b in list)
            {
                if (b == 61) count += 1;
            }
            temp = Math.Abs(Environment.TickCount - ticks);
            Console.WriteLine("经过的时间为:" + temp);

            Console.WriteLine("开始for查询:");
            ticks = Environment.TickCount;
            count = 0;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == 61) count += 1;
            }
            temp = Math.Abs(Environment.TickCount - ticks);
            Console.WriteLine("经过的时间为:" + temp);


            Console.WriteLine("开始linq查询:");
            ticks = Environment.TickCount;
            count = 0;
            foreach (byte t in list.Where(t => t == 61))
            {
                count += 1;
            }
            temp = Math.Abs(Environment.TickCount - ticks);
            Console.WriteLine("经过的时间为:" + temp);

            Console.ReadLine();
for/foreach/linq效率测试

运行结果

for/foreach/linq效率测试for/foreach/linq效率测试for/foreach/linq效率测试

 

运行了十几次基本结果都一样,不知道能不能下定论了。。。。。

for/foreach/linq效率测试

上一篇:HDU 2050 折线分割平面


下一篇:HDU 1267 下沙的沙子有几粒?