教你50招提升ASP.NET性能(二十):认识你的循环

(31)Know your loops

招数31:

认识你的循环

for is the fastest way of iterating over a collection, foreach is a little slower, and LINQ queries are slowest.
for是遍历集合最快的方法,foreach略慢一些,LINQ查询最慢。

测试代码:

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

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("code test:");

            Stopwatch watch = new Stopwatch();
            // for loop
            watch.Start();
            for (int i = 0; i < 100000; i++) { ; }
            watch.Stop();
            Console.WriteLine("for loop:");
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);

            watch = new Stopwatch();
            // while loop
            watch.Start();
            int loop = 0;
            while (loop < 100000) { loop++; }
            watch.Stop();
            Console.WriteLine("while loop:");
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);

            watch = new Stopwatch();
            // foreach loop
            watch.Start();
            int[] array = new int[100000];
            foreach (int i in array) { ; }
            watch.Stop();
            Console.WriteLine("foreach loop:");
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);

            watch = new Stopwatch();
            // foreach loop
            watch.Start();
            Array.ForEach(array, (i) => { ; });
            watch.Stop();
            Console.WriteLine("lamda loop:");
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);

            Console.ReadLine();
        }
    }
}

 

测试结果:

code test:
for loop:
0.2467
while loop:
0.2666
foreach loop:
0.4867
lamda loop:
0.8728

 

posted @ 2013-08-01 14:13  安布雷拉  阅读(654)  评论(1编辑  收藏  举报