开发者

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

开发者 https://www.devze.com 2023-04-01 11:16 出处:网络
When you need to reset a stream to beginning (e.g. MemoryStream) is it best practice to use stream.Seek(0, SeekOrigin.Begin);

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

stream.Seek(0, SeekOrigin.Begin);

or

stream.Position = 0;

I'v开发者_如何学Goe seen both work fine, but wondered if one was more correct than the other?


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.


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.


If you are working with files (eg: with the FileStream class) it seems Seek(0, SeekOrigin.Begin) is able to keep internal buffer (when possible) while Position=0 will always discard it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号