Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles. Follow galratner on Twitter
foreach vs. List.ForEach vs. an old school for loop

So how fast is List.ForEach and how does it compare to older style looping?

I ran a little test:

   10 static void Main(string[] args)

   11         {

   12             List<string> myList = new List<string>();

   13 

   14             for(int i = 0;i<9999999;i++)

   15                 myList.Add(i.ToString());

   16 

   17             Console.WriteLine("Press ENTER to start");

   18 

   19             while(string.IsNullOrEmpty(Console.ReadLine()))

   20                 Loop(myList);

   21         }

   22 

   23         public static void Loop(List<string> myList)

   24         {

   25             DateTime start = DateTime.Now;

   26 

   27             myList.ForEach(DoSomething);

   28 

   29             Console.WriteLine(DateTime.Now.Subtract(start).ToString());

   30 

   31             start = DateTime.Now;

   32 

   33             foreach (string myString in myList)

   34                 DoSomething(myString);

   35 

   36             Console.WriteLine(DateTime.Now.Subtract(start).ToString());

   37 

   38             start = DateTime.Now;

   39 

   40             for (int i = 0; i < myList.Count; i++)

   41                 DoSomething(myList[i]);

   42 

   43             Console.WriteLine(DateTime.Now.Subtract(start).ToString());

   44 

   45         }

   46 

   47         public static void DoSomething(string myString) { }

The Results:

ForEach 1502160

Traditional foreach 4406336

for loop 3204608

As you can tell List.ForEach is More then twice as fast as a for loop and almost three times faster then a Traditional foreach.

The results were more or less the same every time i ran the test. Think about that the next time you are coding a for loop over a collection.


Posted 14 May 2009 6:36 AM by Gal Ratner
Filed under: ,

Powered by Community Server (Non-Commercial Edition), by Telligent Systems