In this article, i will be discussing about the performance of ForEach Vs For Loop.So Let’s get started.

I have data that provides me with 100 posts. And Now i will apply both loops on this data one by one.Let’s First Use ForEach Loop.

ForEach Loop :

ForEach Loop iterates through items in Collection i.e. Lists,Array etc.It’s pretty easy to use ForEach Loop unlike For Loop where we have to provide index number on each iteration.The Syntax for ForEach Loop is As Given Below:

foreach(data_type var_name in collection_variable)
     // statements to be executed

As I applied ForEach Loop on this List containing 100 Posts.The Time Taken to iterate over this list is 0.1036855 seconds.

Now Let’s use For Loop on this List.

For Loop :

The For Loop contain three parts initialization, conditional expression and steps, which are separated by a semicolon.The Basic Syntax for For Loop is as follow:

for (variable initialization; condition; steps)
    //execute this code block as long as condition is satisfied 

As I applied For Loop on this List containing 100 Posts.The Time Taken to iterate over this list is 0.0581698 seconds which is far more less than time taken by ForEach Loop.


 //ForEach Time Taken

                    double forEachResult = 0;
                    double forResult = 0;

                    Stopwatch stopwatch = new Stopwatch();
                    foreach(var a in finalResult)



                    forEachResult = stopwatch.Elapsed.TotalSeconds;


                    //For Loop Time Taken

                    for(int i = 0; i < finalResult.Count; i++) 
                    forResult = stopwatch.Elapsed.TotalSeconds; 
                    Console.WriteLine("ForEach Time Taken :" + forEachResult); 
                    Console.WriteLine("For Loop Time Taken :" + forResult); 
                    Console.WriteLine("Winner Is : " + (forEachResult > forResult ? "For Loop" : "ForEach"));            

Here finalResult is having 100 posts which are consumed from


Also, when it comes to performance, then ‘foreach’ takes much time as compared to the ‘for’ loop because internally, it uses extra memory space, as well as, it uses GetEnumarator() and Next() methods of IEnumerables.

When you want code more clean and readable then you’ re good to use ForEach Loop. But when Performance is concerned then use For Loop.