C# .Net foreach performance comparison Parallel vs Serial vs LINQ

More investigation into the use of parallel and serial loops, again more testing is required to determine conclusive results.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace CsharpParallelForeachDemo
{
    class CsharpParallelForeachExample
    {
        static void Main()
        {
            RunSerial();

            Console.WriteLine();

            RunParallel();

            Console.WriteLine();

            RunLinqSerial();
            
            Console.ReadKey();
        }

        static void RunParallel()
        {
            Console.WriteLine("Processing Parallel Foreach");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            Parallel.ForEach(myRange, range => { var result = range*range; });

            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }

        static void RunSerial()
        {
            Console.WriteLine("Processing Serial Foreach");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            foreach (var range in myRange)
            {
                var result = range * range;
            }
    
            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }

        static void RunLinqSerial()
        {
            Console.WriteLine("Processing Serial LINQ");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            foreach (var result in myRange.Select(range => range * range)){}

            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }
    }
}

Results:

Processing Serial Foreach
Time: 0099253

Processing Parallel Foreach
Time: 088159

Processing Serial LINQ
Time: 0336764

Leave a Reply

Your email address will not be published. Required fields are marked *