FileStream.Seek vs. Buffered Reading

后端 未结 2 878
太阳男子
太阳男子 2021-01-18 07:10

Motivated by this answer I was wondering what\'s going on under the curtain if one uses lots of FileStream.Seek(-1).

For clarity I\'ll repost the answe

相关标签:
2条回答
  • 2021-01-18 07:20

    Going forward vs backward doesn't usually make much difference. The file data is read into the file system cache after the first read, you get a memory-to-memory copy on ReadByte(). That copy isn't sensitive to the file pointer value as long as the data is in the cache. The caching algorithm does however work from the assumption that you'd normally read sequentially. It tries to read ahead, as long as the file sectors are still on the same track. They usually are, unless the disk is heavily fragmented.

    But yes, it is inefficient. You'll get hit with two pinvoke and API calls for each individual byte. There's a fair amount of overhead in that, those same two calls could also read, say, 65 kilobytes with the same amount of overhead. As usual, fix this only when you find it to be a perf bottleneck.

    0 讨论(0)
  • 2021-01-18 07:40

    Here is a pointer on File Caching in Windows

    The behavior may also depends on where physically resides the file (hard disk, network, etc.) as well as local configuration/optimization.

    An also important source of information is the CreateFile API documentation: CreateFile Function

    There is a good section named "Caching Behavior" that tells us at least how you can influence file caching, at least in the unmanaged world.

    0 讨论(0)
提交回复
热议问题