Stream.Seek(0, SeekOrigin.Begin) or Position = 0

后端 未结 2 1250
庸人自扰
庸人自扰 2020-11-29 19:32

When you need to reset a stream to beginning (e.g. MemoryStream) is it best practice to use

stream.Seek(0, SeekOrigin.Begin);

相关标签:
2条回答
  • 2020-11-29 19:58

    You can look at the source code for both methods to find out:

    • Position property
      https://referencesource.microsoft.com/#mscorlib/system/io/memorystream.cs,320
    • Seek method
      https://referencesource.microsoft.com/#mscorlib/system/io/memorystream.cs,482

    The cost is almost identical (3 ifs and some arithmetics). However, this is only true for jumping to absolute offsets like Position = 0 and not relative offsets like Position += 0, in which case Seek seems slightly better.

    However, you should keep in mind that we are talking about performance of a handful of integer arithmetics and if checks, that's like not even accurately measureable with benchmarking methods. Like others already pointed out, there is no significant/detectable difference.

    0 讨论(0)
  • 2020-11-29 20:20

    Use Position when setting an absolute position and Seek when setting a relative position. Both are provided for convenience so you can choose one that fits the style and readability of your code. Accessing Position requires the stream be seekable so they're safely interchangeable.

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