Title: Use PLINQ to select even numbers from an array in C#
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 the example to experiment with it and to see additional details.
|