Use PLINQ to select even numbers from an array in C#

[PLINQ]

This example is really a demonstration of PLINQ, since you probably won’t need to use this technique to find even numbers. (If you do need to generate even numbers, it’s a lot faster and easier to simply pick random numbers and then double them.)

Note that PLINQ was introduced in .NET Framework 4.0. That version was first included in Visual Studio 2010, so this example uses that version.

Parallel LINQ (PLINQ), which enables LINQ to use multiple cores or CPUs if your computer has them, is remarkably easy to use. Simply add a call to the AsParallel method to whatever collection of objects your LINQ query is searching.

This example generates an array of random numbers. It then uses LINQ and PLINQ to search the array for even numbers. The following code shows the LINQ query.

var linq_query =
    from int number in numbers
    where number % 2 == 0
    select number;

The following code shows the PLINQ query with the call to AsParallel highlighted in blue.

var plinq_query =
    from int number in numbers.AsParallel()
    where number % 2 == 0
    select number;

It’s that simple!

If you look at the program’s image, you’ll see that searching 10 million random numbers took 0.49 seconds using LINQ but only 0.39 seconds using PLINQ. My computer is a dual-core system, so PLINQ is considerably faster. The overhead required to use both cores slows things down a bit so the PLINQ query doesn’t take exactly half as long as the LINQ query, but the speed up is considerable.

The example program contains other code that times the queries and displays up to 1,000 numbers in each ListBox. Download the example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in LINQ, performance and tagged , , , , , , , , , , . Bookmark the permalink.

3 Responses to Use PLINQ to select even numbers from an array in C#

  1. Scott says:

    Change the ‘where’ to this:

    where (number & 0x01) == 0

    More often than not, you’ll see substantial gains.

  2. Rod Stephens says:

    True. In this example, I save about 20% of the time. It’s a nice change!

    In general I try to avoid tricks like this that make the code a bit harder to read. But if you’re looking at a really big array, you may want to do this. (Add a comment to make it easier to figure out what the code is doing.)

  3. Pingback: Use PLINQ to select prime numbers from an array in C# - C# HelperC# Helper

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.