220

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
ConfusedNoob
  • 9,826
  • 14
  • 64
  • 85

3 Answers3

205

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.

d219
  • 2,707
  • 5
  • 31
  • 36
gordy
  • 9,360
  • 1
  • 31
  • 43
  • 67
    I use the property even for relative positions: `stream.Position += 10;` seems pretty readable to me. – Jon Skeet Aug 30 '11 at 05:30
  • 8
    Is there a speed difference between using SeekOrigin.Begin and SeekOrigin.Current? – gonzobrains Aug 21 '13 at 23:21
  • 8
    @gonzobrains ["Return Value: The new position within the stream, calculated by combining the initial reference point and the offset."](http://msdn.microsoft.com/en-us/library/system.io.memorystream.seek.aspx). So the combining costs a little bit more than just setting the position directly. Practically it means nothing but nit-picking. ))) – user808128 Oct 08 '13 at 09:21
25

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
ArekBulski
  • 4,520
  • 4
  • 39
  • 61
5

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.

tigrou
  • 4,236
  • 5
  • 33
  • 59