Sunday, March 10, 2013

Performance analyze for loop and foreach

Hi, Friends
In this blog we discussed about Performance analyze of for loop and foreach
Which one gives better performance? for or foreach 
just right two simple methods  
public static void TestFor()
            Stopwatch stopwatch = Stopwatch.StartNew();
            int[] myInterger = new int[1];
            int total = 0;
            for (int i = 0; i < myInterger.Length; i++)
                total += myInterger[i];
            Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
        public static void TestForeach()
            Stopwatch stopwatchForeach = Stopwatch.StartNew();
            int[] myInterger1 = new int[1];
            int totall = 0;
            foreach (int i in myInterger1)
                totall += i;
            Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
Then i ran the above code the result was foreach loop Time Elapsed=00:00:00.0000003,
for loop Time Elapsed= 00:00:00.0001462. i think we want high performance code. we would use foreach

No comments:

Post a Comment