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

后端 未结 2 1330
庸人自扰
庸人自扰 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.

提交回复
热议问题