Batch Processing With Directory.EnumerateFiles

In case one wants to retrieve files from catalog Directory.GetFiles is a simple answer sufficient for most scenarios. However, when you deal with a large amount of data you might need more advanced techniques.
 
Example
 
Let’s assume you have a big data solution and you need to process a directory that contains 200000 files. For each file, you extract some basic info
  1. public record FileProcessingDto  
  2. {  
  3.     public string FullPath { getset; }  
  4.     public long Size { getset; }  
  5.     public string FileNameWithoutExtension { getset; }  
  6.     public string Hash { getinternal set; }  
  7. }  
Note how we conveniently use novel C# 9 record types for our DTO here.
 
After that, we send extracted info for further processing. Let’s emulate it with the following snippet
  1. public class FileProcessingService  
  2. {  
  3.     public Task Process(IReadOnlyCollection<FileProcessingDto> files, CancellationToken cancellationToken = default)  
  4.     {  
  5.         files.Select(p =>  
  6.         {  
  7.             Console.WriteLine($"Processing {p.FileNameWithoutExtension} located at {p.FullPath} of size {p.Size} bytes");  
  8.             return p;  
  9.         });  
  10.   
  11.         return Task.Delay(TimeSpan.FromMilliseconds(20), cancellationToken);  
  12.     }  
  13. }  
Now the final piece is extracting info and calling the service
  1. public class Worker  
  2. {  
  3.     public const string Path = @"path to 200k files";  
  4.     private readonly FileProcessingService _processingService;  
  5.   
  6.     public Worker()  
  7.     {  
  8.         _processingService = new FileProcessingService();  
  9.     }  
  10.   
  11.     private string CalculateHash(string file)  
  12.     {  
  13.         using (var md5Instance = MD5.Create())  
  14.         {  
  15.             using (var stream = File.OpenRead(file))  
  16.             {  
  17.                 var hashResult = md5Instance.ComputeHash(stream);  
  18.                 return BitConverter.ToString(hashResult)  
  19.                     .Replace("-""", StringComparison.OrdinalIgnoreCase)  
  20.                     .ToLowerInvariant();  
  21.             }  
  22.         }  
  23.     }  
  24.   
  25.     private FileProcessingDto MapToDto(string file)  
  26.     {  
  27.         var fileInfo = new FileInfo(file);  
  28.         return new FileProcessingDto()  
  29.         {  
  30.             FullPath = file,  
  31.             Size = fileInfo.Length,  
  32.             FileNameWithoutExtension = fileInfo.Name,  
  33.             Hash = CalculateHash(file)  
  34.         };  
  35.     }  
  36.   
  37.     public Task DoWork()  
  38.     {  
  39.         var files = Directory.GetFiles(Path)  
  40.             .Select(p => MapToDto(p))  
  41.             .ToList();  
  42.   
  43.         return _processingService.Process(files);  
  44.     }  
  45. }  
Note that here we act in a naive fashion and extract all files via Directory.GetFiles(Path) in one take.
 
However, once you run this code via
  1. await new Worker().DoWork()  
you’ll notice that results are far from satisfying and the application is consuming memory extensively.
 

Directory.EnumerateFiles to the rescue

 
The thing with Directory.EnumerateFiles is that it returns IEnumerable<string> thus allowing us to fetch collection items one by one. This in turn prevents us from excessive use of memory while loading huge amounts of data at once.
 
Still, as you may have noticed FileProcessingService.Process has delay coded in it (sort of I/O operation we emulate with simple delay). In a real-world scenario, this might be a call to an external HTTP-endpoint or work with the storage. This brings us to the conclusion that calling FileProcessingService.Process 200 000 times might be inefficient.
 
That’s why we’re going to load reasonable batches of data into memory at once.
 
The reworked code looks as follows
  1. public class WorkerImproved  
  2. {  
  3.     //omitted for brevity  
  4.   
  5.     public async Task DoWork()  
  6.     {  
  7.         const int batchSize = 10000;  
  8.         var files = Directory.EnumerateFiles(Path);  
  9.         var count = 0;  
  10.         var filesToProcess = new List<FileProcessingDto>(batchSize);  
  11.   
  12.         foreach (var file in files)  
  13.         {  
  14.             count++;  
  15.             filesToProcess.Add(MapToDto(file));  
  16.             if (count == batchSize)  
  17.             {  
  18.                 await _processingService.Process(filesToProcess);  
  19.                 count = 0;  
  20.                 filesToProcess.Clear();  
  21.             }  
  22.   
  23.         }  
  24.         if (filesToProcess.Any())  
  25.         {  
  26.             await _processingService.Process(filesToProcess);  
  27.         }  
  28.     }  
  29. }  
Here we enumerate collection with foreach and once we reach the size of the batch we process it and flush the collection. The only interesting moment here is to call service one last time after we exit the loop in order to flush remaining items.
 

Evaluation

 
Results produced by Benchmark.NET are pretty convincing
 
 
Few words on batch processing
 
In this article we took a glance at the common pattern in software engineering. Batches of reasonable amount help us to beat both I/O penalty of working in an item-by-item fashion and excessive memory consumption of loading all items in memory at once.
 
As a rule, you should strive for using batch APIs when doing I/O operations for multiple items. And once the number of items becomes high you should think about splitting these items into batches.
 
Few words on return types
 
Quite often when dealing with codebases I see code similar to the following 
  1. public IEnumerable<int> Numbers => new List<int> { 1, 2, 3 };  
I would argue that this code violates Postel’s principle and the thing that follows from it is that as a consumer of a property I have can’t figure out whether I can enumerate items one by one or if they are just loaded at once in memory.
 
This is a reason I suggest being more specific about return type i.e.
  1. public IList<int> Numbers => new List<int> { 1, 2, 3 };  

Conclusion

 
Batching is a nice technique that allows you to handle big amounts of data gracefully. Directory.EnumerateFiles is the API that allows you to organize batch processing for the directory with a large number of files.