Filestream and BufferedStream

I am a little surprised we don’t get this question more often given the java story around buffered IO… but it came up today on an internal perf alias:



Is there any benefit in using a BufferedStream class over a FileStream if I can already specify a buffer size in the constructor of the FileStream class?


Answer (from Brian Grunkemeyer, dev for the System.IO namespace):

No, there is zero benefit from wrapping a BufferedStream around a FileStream.  We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance (Pit of Success).  In fact, I don’t think there are any Streams in the .NET Framework that require it, but it might be needed by custom Stream implementations if they do not do buffering by default.

Comments (6)

  1. While I can certainly appreciate this reasoning, I dearly miss an unbuffered Stream. For some applications buffering can hurt performance. While I’m at it, I’d also like to see a way to call FlushFileBuffers on a stream (without using P/Invoke).

  2. Stephen Gennard says:

    Buffered I/O is great if you have exclusive access to the file but if the file is being shared between applications it is real pain.

    If you have anything other than "FileShare.None" then you need to ensure that you invoke .Flush() or create the FileStream with a buffer size of one character.

    Why can’t FileStream notice that use FileShare.Read/Write/ReadWrite and avoid doing any buffered I/O?

  3. Joku says:

    What i don’t understand: Why force the devs do a lot of work regarding improving the startup times when a seemingly more sensible would be:

    a) Have the OS/FS monitor what files are being loaded after say .exe is ran, and then either rearrange the files sequentially on the hard drive based on most common load pattern, or if space is of no issue (like with todays hdd’s), have the dll’s have a master copy on one place and mirror them around the hdd so that for every app they can be loaded in a one sequential read even if these resources are shared by many apps. I spend a lot of time just defragmenting to keep the performance good, and it still isn’t good enough as the defragmenting program does not have a clue of how i use the files.

    b) Track what assemblies are loaded on cold starts and then move them to be always in memory from the point Windows loads. Could need some tweaks from the OS standpoint, but rather that than having every .net dev to ponder with the startup time issues themselves.