Parallel foreach vs foreach performance

Parallel foreach vs foreach performance

DEMO
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
 public static void Main()
 {
  string[] colors =
  {
  "1. Red", "2. Green", "3. Blue", "4. Yellow", "5. White", "6. Black", "7. Violet", "8. Brown", "9. Orange", "10. Pink"
  }

  ;
  Console.WriteLine("Using Parallel.ForEach");
  //start the stopwatch for "Parallel.ForEach"
  var sw = Stopwatch.StartNew();
  Parallel.ForEach(colors, color =>
  {
   Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
   Thread.Sleep(10);
  }

  );
  Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);
  Console.WriteLine("\nTraditional foreach loop");
  //start the stopwatch for "for" loop
  sw = Stopwatch.StartNew();
  foreach (string color in colors)
  {
   Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
   Thread.Sleep(10);
  }

  Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
 }
}

DEMO

Parallel foreach vs foreach performance Parallel foreach vs foreach performance Reviewed by Bhaumik Patel on 6:08 AM Rating: 5