Files
dotnet-runtime/src/libraries/System.IO.FileSystem
Stephen Toub 0ce419eaa6 Remove buffer allocation from File.ReadAllBytes
ReadAllBytes is creating a FileStream with the default buffer size of 4K.  Since we've already allocated a byte array large enough to hold the entire file, the internal buffer allocated in FileStream is pure overhead, both for the allocation itself and also for the extra copy of data through the buffer.

This commit fixes this simply by explicitly setting the bufferSize to 1.  FileStream lazily-allocates the buffer, only creating and using it if it needs it.  If a read comes in for a size greater than or equal to the bufferSize, it'll skip the buffer.  So, previously, when reading a file > 4K in size, the buffer would be avoided; now it's also avoided for files <= 4K in size.

A microbenchmark repeatedly caling ReadAllBytes showed that with this fix the number of gen0 GCs caused by its usage dropped anywhere from 0-10x, depending on the size of the file being read.  Throughput improved by a few percentage points as well.

(Note that I also tried this same change for WriteAllBytes.  While it did have a similar effect on gen0 GCs, it caused a surprising regression in throughput, upwards of 20%, and I did not further dig into why.  I also noticed that at the moment FileStream in .NET Core is defaulting to useAsync=true, which is different from the desktop and doesn't make much sense for {Read/Write}AllBytes; if that default remains the same, we should explicitly set useAsync=false for these methods.)


Commit migrated from https://github.com/dotnet/corefx/commit/7f84dfbc13bba30caf8938ca1edd565ba2f42c62
2015-01-31 22:54:44 -05:00
..