Adventures of a wannabe geek!

Ranting within

Speed of for Loop vs for Each Loop

Tonight i seen, via Twitter, that it was potentially faster to iterate through a collection with a For loop rather than a For Each loop. I didn’t believe this [being my usual sceptical self]. Therefore i thought i’d write some sample code to either support the theory and prove it right or to quash it.


        static void GetIEnumberableResults()
            //Small Method call in order to get an IEnumerable
            //Then parse this IEnumerable firstly over a For Loop
            //Then over a ForEach Loop - Each Method Returned a TimeSpan
            var strings = GetStrings();
            var forLoopElapsedTimespan = GetForLoopElapsed_ForStrings(strings);
            var forEachLoopElapsedTimeSpan = GetForEachLoopElapsed_ForString(strings);

            Console.WriteLine("Results For IEnumberable");
            CreateResults(forLoopElapsedTimespan, forEachLoopElapsedTimeSpan);


I started with a simple IEnumberable<string> and iterated over this. I expected this to tell me that ForEach was faster than a For loop as this is what i was expecting. The results are below:


I was then told that the size of the collection being iterated over was a char[] of approx 65000. There was a challenge if ever i needed one. I created a char[] of a huge size [6 8000+] ad ran the same iteration over the array.

        static void GetCharArrayResults()
            //Small Method call in order to get char[] of size 68000 +
            //Then parse this char[] firstly over a For Loop
            //Then over a ForEach Loop - Each Method Returned a TimeSpan
            var chars = GetChars();
            var forLoopElapsed = GetForLoopElapsed_ForCharArray(chars);
            var forEachLoopElapsed = GetForEachLoopElapsed_ForCharArray(chars);

            Console.WriteLine(string.Format("Results for char[] of size {0}", chars.Length));
            CreateResults(forLoopElapsed, forEachLoopElapsed);

Again i expected the ForEach loop to be faster. The results are below:


i have absolutely no idea what’s causing this - so if any of you can let me know that would be fantastic. This has really brought out the proper geek in me :)