.Net C# parallel Linq (PLINQ) and ToList() question

I took a question related to a previous post and about the use of ToList() in a PLINQ query, I put together a test that shows the quickest way to execute a call to ToList(). The results indicate that it’s much faster to call ToList() after LINQ execution.

using System;
using System.Diagnostics;
using System.Linq;

namespace CsharpParallelLinqExample
{
    class CsharpParallelLinqDemo
    {
        static void Main()
        {
            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList()");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                        .WithDegreeOfParallelism(i)
                        .Select(x => x).ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList() after PLINQ execution");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.ReadKey();
        }
    }
}

Returns:

Processing and calling .ToList()
Number of cores: 1 Time: 102726
Number of cores: 2 Time: 0653831
Number of cores: 3 Time: 0599256
Number of cores: 4 Time: 0595193

Processing and calling .ToList() after PLINQ execution
Number of cores: 1 Time: 0917514
Number of cores: 2 Time: 0629758
Number of cores: 3 Time: 052276
Number of cores: 4 Time: 057208

One thought on “.Net C# parallel Linq (PLINQ) and ToList() question”

  1. Interesting. I wonder whether it’s the parallelism that causes ToList() to run 5x slower, or whether it’s inherent in running .ToList() on the back of the LINQ… we use that construct quite a bit because ReSharper complains that without it the resulting IEnumerable implementation is ambiguous. The IL might give clues as to what is actually being executed.

    Rich

Leave a Reply

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