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

C#.NetStream

C# Problem Overview


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've seen both work fine, but wondered if one was more correct than the other?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

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.

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionConfusedNoobView Question on Stackoverflow
Solution 1 - C#gordyView Answer on Stackoverflow
Solution 2 - C#ArekBulskiView Answer on Stackoverflow
Solution 3 - C#tigrouView Answer on Stackoverflow