Upgrade to Linq AsParallel

I was amazed & delighted a couple of weeks ago when resharper 5 suddenly decided a huge piece of code I was refactoring could be converted in to linq – my esteemed ex-colleague John Rayner has already blogged about this so no need to repeat it (check out the amazing chunk of code it reduced). I showed it to someone at work though and he asked the question ‘why?’, as to him the original was more readable. I tend to agree with John that linq (methods chaining) is more readable now, and as everyone groks it I’m sure you will too. However I have come up with another neat reason ‘why’ – you can parallelize your (thread-safe) .Net 4 code for free.

Run this code:

int c = 0; 
foreach (var i in Enumerable.Range(1, 1000000))
{
    if (IsPrime(i))
    {
        c++;
    }
}
// ... 
static bool IsPrime(int val)
{
    foreach (var i in Enumerable.Range(2, val))
    {
        if (val % i == 0)
        {
            return false;
        }
    }
    return true;
}

Watch it churn a single CPU (to be fair this didn't dent my CPU too much, but it did take over 2 minutes)

image

upgrade to linq (alt-enter on the foreach)

int c = Enumerable.Range(1, 1000000)
                .Count(IsPrime)

stick in a strategic AsParallel, and watch it use up all of your CPUs nicely.

int c = Enumerable.Range(1, 1000000)
    .AsParallel()
    .Count(IsPrime);

image

The latter took ~30s.

Credit here to this Christer for the IsPrime AsParallel example, I really did just paste 2 blogs together here but I hope someone finds it useful ;)

Older Posts