Performance Of Loops In C#

In this article, we will dive deep into the performance of C# Loops.

Introduction
 
I am often asked by some people/colleagues about "which loop is faster?", "Which loop has high performance?" etc. I have heard that the For loop is faster than the Foreach loop but I have never tried it before. So, I decided to see how big the difference is among all the loops and which one is faster on array and list in terms of speed and performance.
 
Let's start to find out the best C# loop. For these, I'll be creating a console application in Visual Studio 2017. 
 
First, I'm going to create one class namely "CustomStopwatch" which helps to track the starting and ending times of loops. 
  1. using System;  
  2. using System.Diagnostics;  
  3.   
  4. namespace ConsoleApp2  
  5. {  
  6.     public class CustomStopwatch : Stopwatch  
  7.     {  
  8.   
  9.         public DateTime? StartAt { getprivate set; }  
  10.         public DateTime? EndAt { getprivate set; }  
  11.   
  12.   
  13.         public void Start()  
  14.         {  
  15.             StartAt = DateTime.Now;  
  16.   
  17.             base.Start();  
  18.         }  
  19.   
  20.         public void Stop()  
  21.         {  
  22.             EndAt = DateTime.Now;  
  23.   
  24.             base.Stop();  
  25.         }  
  26.   
  27.         public void Reset()  
  28.         {  
  29.             StartAt = null;  
  30.             EndAt = null;  
  31.   
  32.             base.Reset();  
  33.         }  
  34.   
  35.         public void Restart()  
  36.         {  
  37.             StartAt = DateTime.Now;  
  38.             EndAt = null;  
  39.   
  40.             base.Restart();  
  41.         }  
  42.   
  43.     }  
  44. }  
Performance Of The Loops In C#
 
Now, it is time to write code in Program.cs class. First, I'm going to implement a For loop on,
  • Single integer
  • Array
  • List
  1. using System;  
  2. using System.Linq;  
  3.   
  4. namespace ConsoleApp2  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             CustomStopwatch sw = new CustomStopwatch();  
  11.             sw.Start();  
  12.             for (int i = 0; i < 10000; i++) Console.WriteLine(i);  
  13.             sw.Stop();  
  14.   
  15.             CustomStopwatch sw1 = new CustomStopwatch();  
  16.             int[] array = Enumerable.Range(0, 10000).ToArray();  
  17.             sw1.Start();  
  18.             for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]);  
  19.             sw1.Stop();  
  20.   
  21.             CustomStopwatch sw2 = new CustomStopwatch();  
  22.             var arrList = array.ToList();  
  23.             sw2.Start();  
  24.             for (int i = 0; i < arrList.Count; i++) Console.WriteLine(arrList[i]);  
  25.             sw2.Stop();  
  26.   
  27.             Console.WriteLine($"for Time elapsed: {sw.ElapsedMilliseconds} Milliseconds, StartAt: {sw.StartAt.Value}, EndAt: {sw.EndAt.Value}");  
  28.             Console.WriteLine($"for on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
  29.             Console.WriteLine($"for on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
  30.             Console.ReadKey();  
  31.         }  
  32.   
  33.     }  
  34. }  
Performance Of The Loops In C#
 
Let's run the script to see output and execution time in milliseconds. 
 
Performance Of The Loops In C#
 
As per my output, the For loop on the list is faster. 
 
Let's compare the Foreach loop on the list and array.
  1. using System;  
  2. using System.Linq;  
  3.   
  4. namespace ConsoleApp2  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             int[] array = Enumerable.Range(0, 10000).ToArray();  
  11.             var arrList = array.ToList();  
  12.   
  13.             CustomStopwatch sw1 = new CustomStopwatch();  
  14.             sw1.Start();  
  15.             foreach (var arr in array) Console.WriteLine(arr);  
  16.             sw1.Stop();  
  17.   
  18.             CustomStopwatch sw2 = new CustomStopwatch();  
  19.             sw2.Start();  
  20.             foreach (var arr in arrList) Console.WriteLine(arr);  
  21.             sw2.Stop();  
  22.   
  23.             Console.Clear();  
  24.             Console.WriteLine($"for each on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
  25.             Console.WriteLine($"for each on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
  26.             Console.ReadKey();  
  27.         }  
  28.     }  
  29. }  
Performance Of The Loops In C#
 
Let's run to see output and execution time in milliseconds.
 
Performance Of The Loops In C#
 
Here, the Foreach loop on the list is faster.
 
Let's compare While loop on the list and an array.
  1. using System;  
  2. using System.Linq;  
  3.   
  4. namespace ConsoleApp2  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             int[] array = Enumerable.Range(0, 10000).ToArray();  
  11.             var arrList = array.ToList();  
  12.   
  13.             CustomStopwatch sw1 = new CustomStopwatch();  
  14.             sw1.Start();  
  15.             int i = 0;  
  16.             while (i != array.Length) Console.WriteLine(array[i++]);  
  17.             sw1.Stop();  
  18.   
  19.             CustomStopwatch sw2 = new CustomStopwatch();  
  20.             sw2.Start();  
  21.             i = 0;  
  22.             while (i != arrList.Count) Console.WriteLine(arrList[i++]);  
  23.             sw2.Stop();  
  24.   
  25.             Console.Clear();  
  26.             Console.WriteLine($"while on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
  27.             Console.WriteLine($"while on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
  28.             Console.ReadKey();  
  29.         }  
  30.     }  
  31. }  
Performance Of The Loops In C#
 
And the output of while loop is as below. 
 
Performance Of The Loops In C#
 
While loop on the list is faster.
 
Conclusion 
 
This article covers a quick comparison of For, Foreach, and While loop on array and list. As I said before, an Array is faster than List but as per my observation (in terms of iteration), List is faster as we can see in the outputs. I think it depends on data and the way you use the data. My personal suggestion is that we should use a list instead of an array for below reasons.
  • In array, we need to know an array size, we can't change array size (we have the Resize() method but it will change reference) where a list can grow after it's created.
  • In list, we don't need to worry about list size or index out of bound exception.
  • The list provides lots of helpful methods like Add, Find, etc.
  • Easy to read. 
Please give your valuable feedback/comments/questions about this article below. Please let me know how you like and understand this article and how I could improve it.