views:

272

answers:

3

I would like to know whether using a BinaryReader on a MemoryStream created from a byte array (byte[]) would reduce performance significantly.

There is binary data I want to read, and I get that data as an array of bytes. I am currently deciding between two approaches to read the data, and have to implement many reading methods accordingly. After each reading action, I need the position right after the read data, and therefor I am considering using a BinaryReader. The first, non-BinaryReader approach:

object Read(byte[] data, ref int offset);

The second approach:

object Read(BinaryReader reader);

Such Read() methods will be called very often, in succession on the same data until all data has been read.

So, using a BinaryReader feels more natural, but has it much impact on the performance?

A: 

If using a BinaryReader feels more natural, do that. I highly doubt there's any noticable performance hit vs reading from an array.

zildjohn01
Why do you doubt that? There are tons of data I need to process this way. While it would certainly be easier to use a BinaryReader (because I may use ReadUInt32() and such methods), it is really the best thing to do?
Virtlink
@Virtlink, make a small test and benchmark it. Then decide if using a Reader will impact performance.
Mikael Svenson
+2  A: 

You'll create a fair amount of garbage for each call to Read(byte[]). There will be 40 bytes for the MemoryStream, I stopped counting at 64 bytes for the BinaryReader. Dispose is also normally used, although it doesn't do anything. Whether that overhead matters is impossible to tell from your question.

I'd personally prefer the Read(BinaryReader) overload, not just because it is more efficient. That also gives the flexibility of changing the source of the data. It doesn't have to be in a byte[] anymore, you could feed it from, say, a FileStream or NetworkStream.

Hans Passant
It's not just the signature of the methods. Internally, I'd use OR and shift operations on the bytes of the array for the first approach. Thus no garbage. Would a `BinaryReader` still be preferable?
Virtlink
Erm, you can read a byte[] with BinaryReader as well and OR and shift as much as you need. Getting a byte[] that would be larger than the sum of MS + BR would be the break-even point. Again, not enough info to make the call. This kind of bit-whacking can be a significant maintenance headache btw. Look at BinaryFormatter.
Hans Passant
A: 

Hi Virtlink,

Did you find out which was best for performance? I do a similar thing and would be interested in your results.

ManInMoon
You should have posted a comment instead, as this is not an anwer. I accepted Hans Passant's answer and use BinaryReader in the signature now.
Virtlink