Tuesday, January 30, 2018

In defense of foreach

I recently inherited the project from hell that was abandoned by the technical lead who resigned rather than see it to conclusion. Looking through his code, I see some terrible coding habits such as if/then/else ladders instead of switch statements and an inability to consolidate code or use base classes. However, in this post, I'm going to focus on his refusal to use foreach.

Let's see just how inefficient for loops are compared to foreach. I'm going to create a list of integers and then execute two loops that reference the list elements three times. The stopwatch class will tell me how much time we can save by utilizing foreach.

Create a new console application.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ForEach
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            List<int> l = Enumerable.Range(1, 10000000).ToList<int>();
            int x;

            sw.Start();
            for (int i = 0; i < l.Count; i++)
            {
                x = l[i];
                x = l[i] + 1;
                x = l[i] * 2;
            }

            sw.Stop();
            Console.WriteLine("for i took " + sw.ElapsedMilliseconds.ToString() + "ms");

            sw.Restart();
            foreach (int i in l)
            {
                x = i;
                x = i + 1;
                x = i * 2;
            }

            sw.Stop();
            Console.WriteLine("for each took " + sw.ElapsedMilliseconds.ToString() + "ms");
            Console.ReadKey();
        }
    }
}



On my computer the for i loop takes 107ms and the foreach took 52ms. Quite a significant difference.