Faster (unsafe) BinaryReader in .NET

后端 未结 4 1666
余生分开走
余生分开走 2021-01-31 18:06

I came across a situation where I have a pretty big file that I need to read binary data from.

Consequently, I realized that the default BinaryReader implementation in .

4条回答
  •  隐瞒了意图╮
    2021-01-31 18:45

    I ran into a similar performance issue with BinaryReader/FileStream, and after profiling, I discovered that the problem isn't with FileStream buffering, but instead with this line:

    while (br.BaseStream.Position < br.BaseStream.Length) {
    

    Specifically, the property br.BaseStream.Length on a FileStream makes a (relatively) slow system call to get the file size on each loop. After changing the code to this:

    long length = br.BaseStream.Length;
    while (br.BaseStream.Position < length) {
    

    and using an appropriate buffer size for the FileStream, I achieved similar performance to the MemoryStream example.

提交回复
热议问题