Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PLINQ bad performance

Tags:

c#

plinq

I'm trying to implement PLINQ example but facing following problem My sequential queries are executed faster than parallel queries.

here is the code example:

        Stopwatch sw = new Stopwatch();

        int[] vals = Enumerable.Range(0, Int16.MaxValue).ToArray();

        sw.Start();
        int[] x1 = vals.Where(x => x % 2 == 0).ToArray();
        sw.Stop();
        Console.WriteLine("Sequential Execution {0} milliseconds", sw.ElapsedMilliseconds);


        sw.Restart();
        int[] x2 = vals.AsParallel().Where(x => x % 2 == 0).ToArray();
        sw.Stop();
        Console.WriteLine("Parallel Execution {0} milliseconds", sw.ElapsedMilliseconds);

My machine is Pentium(R) Dual - Core I've also tried on Quad - Core AMD Opteron(tm).

The same result Parallel queries run slower than sequential. Can you please tell me what is my problem?

Thanks.

like image 685
Michael Samteladze Avatar asked Dec 20 '22 20:12

Michael Samteladze


1 Answers

I guess this has to do with some overhead. The collection you iterate is quite small (32k shorts) and the operation performed on those items is trivial.

In such a scenario the partitioning of a collection, filtering and remerging may be much more expensive than performing the same within a single iteration.

If your comparison is more expensive (e.g. searching strings) and your collection grows, you´ll see the results changing.

like image 131
Joachim Kerschbaumer Avatar answered Dec 23 '22 11:12

Joachim Kerschbaumer