39. Directory size, PLINQ style

Turning a LINQ query into a PLINQ query is usually quite simple. The following code shows the SizePLINQ extension method. The difference between this version and the LINQ version is highlighted in bold:

// Use PLINQ to calculate the directory's size.
public static long SizePLINQ(this DirectoryInfo dirinfo,
bool includeSubdirs = false)
{
// Get the files within the directory.
FileInfo[] fileinfos;
if (includeSubdirs)
fileinfos = dirinfo.GetFiles("*", SearchOption.AllDirectories);
else
fileinfos = dirinfo.GetFiles("*",
SearchOption.TopDirectoryOnly);

    // Add the file sizes.
var sizeQuery =
from FileInfo fileinfo in fileinfos.AsParallel()
select fileinfo.Length;
return sizeQuery.Sum();
}

The only difference between the PLINQ and LINQ versions is that the PLINQ version adds .AsParallel() to the from clause. That makes the query system perform loop iterations in parallel.

Unfortunately, the query simply selects the FileInfo objects' Length values. That is a relatively fast operation, so selecting those values in parallel doesn't save much time. In fact, the extra overhead needed to execute the loop in parallel and then use the Sum method to combine the results makes this version of the program slower.

The following screenshot shows a typical run by the example solution. If you look closely, you'll see that the LINQ version runs slightly more slowly than the foreach version, and the PLINQ version runs even more slowly:

The moral of the story is that PLINQ can hurt performance unless the tasks it performs are naturally parallelizable.

Download the DirectorySizePLINQ example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.85.135