FileStream.Seek vs. Buffered Reading

后端 未结 2 879
太阳男子
太阳男子 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.

提交回复
热议问题