Friday, August 3, 2012

[C#] Effective : For vs Foreach

Alought Effective C# Item #11 said : Prefer foreach Loops , but I still saw many test said using For are faster , so , let's test it.

My test code.
public static int[] ArInt = new int[1000]; //2000,4000

        static void Main(string[] args)
        {
            
            var proc = Process.GetCurrentProcess();
            var sTime=proc.TotalProcessorTime;
            for (int i = 0; i < 100000; i++)    //100,000
            {
                DoForEach();
            }
            Console.WriteLine(proc.TotalProcessorTime-sTime);
            Console.WriteLine();
            Console.ReadLine();
        }

        static void DoFor()
        {
            for (int i = 0; i < ArInt.Length; i++)
            {
                DoNothing();
            }
        }

        static void DoForEach()
        {
            foreach (int t in ArInt)
            {
                DoNothing();
            }
        }

        static void DoNothing()        
        {
        }

We give an Integer Array (Size :1000,2000,4000) , For/Foreach loop it do nothing for 100,000 times , get the result and average it. You can check the result on following sheet.


OK, you can see using Foreach Loop are slower than using For Loop over 10% , no big difference , but we are talking about effective , so For Loop win.



No comments:

Post a Comment