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?
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?
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.
stream.Position += 10;
seems pretty readable to me. –
Neurogram You can look at the source code for both methods to find out:
The cost is almost identical (3 if
s 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.
Position
setter defers the call to _strategy.Position. FileStream
use BufferedFileStreamStrategy
as strategy and that one simply call Seek(value, SeekOrigin.Begin). I would say buffer is preserved (to be tested). –
Sinh © 2022 - 2024 — McMap. All rights reserved.
stream.Position = 0;
but I have to agree with @jgauffin, just choose the most readable, both solutions work fine. – Flam