Question

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 therefore 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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top