DirectoryInfo.GetFiles improved in .NET 4

A nice improvement in .NET 4 is that the following code runs significantly faster than it did under .NET 3.5:

new DirectoryInfo(folderPath)
    .GetFiles()
    .Select<FileInfo, long>(fi => fi.Length)
    .ToList();

In .NET 3.5, the Length property (as well as most of the other properties on FileInfo) is fetched lazily; accessing the property hits the filesystem again for each file returned by GetFiles, incurring a substantial speed penalty. In .NET 4, GetFiles uses the information already returned by the OS when enumerating the contents of the directory to pre-populate the values of the FileInfo properties, avoiding subsequent filesystem accesses.

For a folder containing several thousand files, the .NET 4 implementation can be from three times (on a local drive) to 50 times (on a network path) faster.

For more information on this and other changes, see Justin Van Patten’s MSDN magazine article, What’s New in the Base Class Libraries in .NET Framework 4.

Posted by Bradley Grainger on December 16, 2010