Parallel.ForEach() Vs Foreach() Loop in C#

C# Foreach loop

Foreach loop in C# runs upon a single thread and processing takes place sequentially one by one. Foreach loop is a basic feature of C# and it is available from C# 1.0. Its execution is slower than the Parallel.Foreach in most of the cases.

C# Parallel.ForEach loop

Parallel.ForEach loop in C# runs upon multiple threads and processing takes place in a  parallel way. Parallel.ForEach loop is not a basic feature of C# and it is available from C# 4.0 and above. Before C# 4.0 we cannot use it. Its execution is faster than foreach in most of the cases. To use Parallel.ForEach loop we need to import System.Threading.Tasks namespace in using directive.

But you know your application well and you can decide which one you want to use.

I am giving 2 examples, in the first example traditional foreach loop is faster than Parallel.foreach loop where as in second example traditional foreach loop is very slow as compared to Parallel.foreach.

Example 1: Parallel.ForEach loop is slower than Traditional Foreach loop.

List<string> fruits = new List<string>();  
  fruits.Add("Apple");  
  fruits.Add("Banana");  
  fruits.Add("Bilberry");  
  fruits.Add("Blackberry");  
  fruits.Add("Blackcurrant");  
  fruits.Add("Blueberry");  
  fruits.Add("Cherry");  
  fruits.Add("Coconut");  
  fruits.Add("Cranberry");  
  fruits.Add("Date");  
  fruits.Add("Fig");  
  fruits.Add("Grape");  
  fruits.Add("Guava");  
  fruits.Add("Jack-fruit");  
  fruits.Add("Kiwi fruit");  
  fruits.Add("Lemon");  
  fruits.Add("Lime");  
  fruits.Add("Lychee");  
  fruits.Add("Mango");  
  fruits.Add("Melon");  
  fruits.Add("Olive");  
  fruits.Add("Orange");  
  fruits.Add("Papaya");  
  fruits.Add("Plum");  
  fruits.Add("Pineapple");  
  fruits.Add("Pomegranate");  
  
  Console.WriteLine("Printing list using foreach loop\n");  
  
  var stopWatch = Stopwatch.StartNew();  
  foreach (string fruit in fruits)  
  {  
      Console.WriteLine("Fruit Name: {0}, Thread Id= {1}", fruit, Thread.CurrentThread.ManagedThreadId);  
  }  
  Console.WriteLine("foreach loop execution time = {0} seconds\n", stopWatch.Elapsed.TotalSeconds);  
  Console.WriteLine("Printing list using Parallel.ForEach");  
  
  
  stopWatch = Stopwatch.StartNew();  
  Parallel.ForEach(fruits, fruit =>  
  {  
      Console.WriteLine("Fruit Name: {0}, Thread Id= {1}", fruit, Thread.CurrentThread.ManagedThreadId);  
  
  }  
  );  
  Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", stopWatch.Elapsed.TotalSeconds);  
  Console.Read();

Output

Execution time

Output

Example 2: Parallel.ForEach loop is faster than Traditional Foreach loop.

Traditional Foreach 

var stopWatch = Stopwatch.StartNew();  
PointF firstLocation = new PointF(10 f, 10 f);  
PointF secondLocation = new PointF(10 f, 50 f);  
foreach(string file in Directory.GetFiles(@ "D:\Images"))  
{  
    Bitmap bitmap = (Bitmap) Image.FromFile(file);  
    using(Graphics graphics = Graphics.FromImage(bitmap))  
    {  
        using(Font arialFont = new Font("Arial", 10))  
        {  
            graphics.DrawString("Banketeshvar", arialFont, Brushes.Blue, firstLocation);  
            graphics.DrawString("Narayan", arialFont, Brushes.Red, secondLocation);  
        }  
    }  
    bitmap.Save(Path.GetDirectoryName(file) + "Foreachloop" + "\\" + Path.GetFileNameWithoutExtension(file) + Guid.NewGuid()  
        .ToString() + ".jpg");  
}  
Console.WriteLine("foreach loop execution time = {0} seconds\n", stopWatch.Elapsed.TotalSeconds); 

Output

cmd

Parallel.foreach

var stopWatch = Stopwatch.StartNew();  
PointF firstLocation = new PointF(10 f, 10 f);  
PointF secondLocation = new PointF(10 f, 50 f);  
Parallel.ForEach(Directory.GetFiles(@ "D:\Images"), file =>  
{  
    Bitmap bitmap = (Bitmap) Image.FromFile(file);  
    using(Graphics graphics = Graphics.FromImage(bitmap))  
    {  
        using(Font arialFont = new Font("Arial", 10))  
        {  
            graphics.DrawString("Banketeshvar", arialFont, Brushes.Blue, firstLocation);  
            graphics.DrawString("Narayan", arialFont, Brushes.Red, secondLocation);  
        }  
    }  
    bitmap.Save(Path.GetDirectoryName(file) + "Parallel" + "\\" + Path.GetFileNameWithoutExtension(file) + Guid.NewGuid()  
        .ToString() + ".jpg");  
});  
Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", stopWatch.Elapsed.TotalSeconds);  
Console.Read();

Output

run

To test the performance of the above code, I have used around 150 images in both cases.

You can see that if you are doing any bulk task inside the foreach loop then parallel.foreach is very fast so you can go for parallel.foreach. But if you just iterating and doing a very little task inside loop then go for traditional for loop


Similar Articles