Tuesday, May 27, 2008

The Myth of for being faster than foreach

You probably, like me, heard this so many times that for is faster than foreach and you should use it whenever you can. Well, today I wanted to know how much this is true so I did a little test (find below the test and results). As you can see in the results of the test they are both identical but as I find using foreach is much more convenient for many reasons (including thread safety in some scenarios) so it makes more sense to use foreach whenever possible.

More details:

The release build was used in the test
Software used in the test:
  • Windows XP Pro SP2
  • .NET Framework 2.0

The specs of my computer (where the test was done) are:
  • CPU Intel 1.6GHz Dual Core
  • 1024 MB RAM


Used Code
using System;
using System.Collections.Generic;
using System.Text;

namespace for_vs_foreach
{
    class Program
    {
        static void Main(string[] args)
        {
            const int LOOP_COUNT = 10000000;
            int myVar;
            MyCustomObject[] customObjects = new MyCustomObject[LOOP_COUNT];
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                customObjects[i] = new MyCustomObject(i);
            }

            System.Threading.Thread.Sleep(1000);

            // foreach
            //
            DateTime beforeForeach = DateTime.Now;
            foreach (MyCustomObject customObject in customObjects)
            {
                myVar = customObject.Var;
            }
            DateTime afterForeach = DateTime.Now;

            // for
            //
            DateTime beforeFor = DateTime.Now;
            for (int i = 0; i < LOOP_COUNT; i++)
            {
                myVar = customObjects[i].Var;
            }
            DateTime afterFor = DateTime.Now;

            Console.WriteLine("{0} (foreach test results)", afterForeach.Subtract(beforeForeach));
            Console.WriteLine("{0} (for test results)", afterFor.Subtract(beforeFor));
            Console.Read();
        }
    }

    public class MyCustomObject
    {
        public MyCustomObject(int var)
        {
            _var = var;
        }

        private int _var;
        public int Var
        {
            get
            {
                return _var;
            }
            set
            {
                _var = value;
            }
        }
    }
}
Results: 00:00:00.0625000 (foreach test results)
00:00:00.0625000 (for test results)

No comments:

Post a Comment