Iterating items in a list - for vs. while vs. foreach

When iterating over the items in list in C# you have at least 3 options as to how you want to do it. This blog post is simply a small journey into exploring the 3 options for, foreach and while seen from a performance perspective.


For this journey I will take a look at the following very simple console application

using System;
using System.Diagnostics;
using System.Linq;

namespace ConsoleApplication1
    internal class Program
        private static void Main(string[] args)
            var iterations = 10000000;
            var test = 0;

            for (var a = 0; a < 50; a++)
                var list1 = Enumerable.Range(0, iterations).ToList();
                var list2 = Enumerable.Range(0, iterations).ToList();
                var list3 = Enumerable.Range(0, iterations).ToList();

                var st = new Stopwatch();
                for (var i = 0; i < list3.Count; i++)
                    test = list3[i];

                var st2 = new Stopwatch();
                foreach (var i in list2)
                    test = i;

                var st3 = new Stopwatch();
                var iterationcount = iterations;
                while (iterationcount-- > 0)
                    test = list1[iterationcount];

                Console.WriteLine("1: [{0}] 2: [{1}] 3: [{2}]", st.ElapsedMilliseconds,
                    st2.ElapsedMilliseconds, st3.ElapsedMilliseconds);

This is a very simple test case just to prove a point

I have a loop where I do 50 test runs and for each test run for each type of loop I create a sample list of 10.000.000 integers and then I simply test each type of loop to see which loop type will give me the fastest access to all my numbers again.


Before doing the test I would consider them more or less equal and I would actual expect the foreach loop to be the fastest because it does not have to continuously index the list. But having run the code multiple times (and even having rearranged the order of the loops), the result always come out similar and looking somewhat like this

Loop performance


So most of the time the for-loop is the slowest. The foreach-loop is in second and then the while-loop is actually the fastest.


Off course your mileage may vary depending on what you are trying to do, but if you need to squeeze out the last milliseconds in your app, you can consider which kind of loops that you are using.

Comments are closed